ifcopenshell.geom

Geometry processing and analysis

IFC may define geometry explicitly (such as meshes) or implicitly (such as parametric extrusions). This module provides methods to extract geometric definitions in IFC into explicitly tessellated triangles or OpenCASCADE Breps for further processing.

This is typically needed when writing software to visualise or analyse geometry. See also ifcopenshell.util.shape for deriving quantities.

Submodules

Package Contents

class ifcopenshell.geom.entity_instance(e, file=None)

Represents an entity (wall, slab, property, etc) of an IFC model

An IFC model consists of entities. Examples of entities include walls, slabs, doors and so on. Entities can also be non-physical things, like properties, systems, construction tasks, colours, geometry, and more.

Entities are defined through an IFC Class. There are hundreds of IFC Classes defined as part of the ISO standard by the buildingSMART International organisation. The IFC Class defines the attributes of an entity, as well as the data types and whether or not an attribute is mandatory or optional.

IfcOpenShell’s API dynamically implements the IFC schema. You will not find documentation about available IFC Classes, or what attributes they have. Please consult the buildingSMART official documentation or start reading Introduction to IFC.

In addition to the Python methods you see documented here, an instantiated entity_instance will have attributes defined by its IFC class. For example, an entity instance which is an IfcWall class will have a Name attribute, and an IfcColourRgb will have a Red attribute. Please consult the buildingSMART official documentation.

Example:

model = ifcopenshell.open(file_path)
walls = model.by_type("IfcWall")
wall = walls[0]

print(wall) # #38=IFCWALL('2MEinnTPbCMwLOgceaQZFu',$,$,'My Wall',$,#52,#47,$,$);
print(wall.is_a()) # IfcWall

# Note: the `Name` attribute is dynamic, based on the IFC class.
print(wall.Name) # My Wall

# Attributes are ordered and may also be accessed via index.
print(wall[3]) # My Wall

print(wall.__class__) # <class 'ifcopenshell.entity_instance'>
attribute_name(attr_idx: int) str

Return the name of a positional attribute of the element

Parameters:

attr_idx (int) – The index of the attribute

Return type:

string

attribute_type(attr: int | str) str

Return the data type of a positional attribute of the element

Parameters:

attr (Union[int, str]) – The index or name of the attribute

Return type:

string

compare(other, op, reverse=False)

Compares with another instance.

For simple types the declaration name is not taken into account:

>>> f = ifcopenshell.file()
>>> f.createIfcInteger(0) < f.createIfcPositiveInteger(1)
True

For entity types the declaration name is taken into account:

>>> f.createIfcWall('a') < f.createIfcWall('b')
True
>>> f.createIfcWallStandardCase('a') < f.createIfcWall('b')
False

Comparing simple types with different underlying types throws an exception:

>>> f.createIfcInteger(0) < f.createIfcLabel('x')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "entity_instance.py", line 371, in compare
    return op(a, b)
TypeError: '<' not supported between instances of 'int' and 'str'
Args:

other (_type_): Right hand side (or lhs when reverse = True) op (_type_): The comparison operator (likely from the operator module) reverse (bool, optional): When true swaps lhs and rhs. Defaults to False.

Returns:

bool: The comparison predicate applied to self and other

get_info(include_identifier=True, recursive=False, return_type=dict, ignore=(), scalar_only=False) dict

Return a dictionary of the entity_instance’s properties (Python and IFC) and their values.

Parameters:
  • include_identifier (bool) – Whether or not to include the STEP numerical identifier

  • recursive (bool) – Whether or not to convert referenced IFC elements into dictionaries too. All attributes also apply recursively

  • return_type (dict|list|other) – The return data type to be casted into

  • ignore (set|list) – A list of attribute names to ignore

  • scalar_only (bool) – Filters out all values that are IFC instances

Returns:

A dictionary of properties and their corresponding values

Return type:

dict

Example:

ifc_file = ifcopenshell.open(file_path)
products = ifc_file.by_type("IfcProduct")
obj_info = products[0].get_info()
print(obj_info.keys())
>>> dict_keys(['Description', 'Name', 'BuildingAddress', 'LongName', 'GlobalId', 'ObjectPlacement', 'OwnerHistory', 'ObjectType',
>>> ...'ElevationOfTerrain', 'CompositionType', 'id', 'Representation', 'type', 'ElevationOfRefHeight'])
get_info_2(include_identifier=True, recursive=False, return_type=dict, ignore=())

More perfomant version of .get_info() but with limited arguments values.

Method has exactly the same signature as .get_info() but it doesn’t support getting information non-recursively.

Currently supported arguments values:
  • include_identifier: True

  • recursive: True (will fail with default False value from .get_info())

  • return_type: dict

  • ignore: () (empty tuple)

id() int

Return the STEP numerical identifier

Return type:

int

is_a() str
is_a(ifc_class: str) bool
is_a(with_schema: bool) str

Return the IFC class name of an instance, or checks if an instance belongs to a class.

The check will also return true if a parent class name is provided.

Parameters:

args (Union[str, bool]) – If specified, is a case insensitive IFC class name to check or if specified as a boolean then will define whether returned IFC class name should include schema name (e.g. “IFC4.IfcWall” if True and “IfcWall” if False). If omitted will act as False.

Returns:

Either the name of the class, or a boolean if it passes the check

Return type:

Union[str, bool]

Example:

f = ifcopenshell.file()
f.create_entity('IfcPerson')
f.is_a()
>>> 'IfcPerson'
f.is_a('IfcPerson')
>>> True
is_entity() bool

Tests whether the instance is an entity type as opposed to a simple data type.

Returns:

bool: True if the instance is an entity

to_string(valid_spf=True) str

Returns a string representation of the current entity instance. Equal to str(self) when valid_spf=False. When valid_spf is True returns a representation of the string that conforms to valid Step Physical File notation. The difference being entity names in upper case and string attribute values with unicode values encoded per the specific control directives.

static unwrap_value(v)
static walk(f: Callable[[Any], bool], g: Callable[[Any], Any], value: Any) Any

Applies a transformation to value based on a given condition.

If value is a nested structure (e.g., a list or a tuple) will apply transformation to it’s elements.

Parameters:
  • f (Callable) – A callable that takes a single argument and returns a boolean value. It represents the condition.

  • g (Callable) – A callable that takes a single argument and returns a transformed value. It represents the transformation.

  • value (Any) – Any object, the input value to be processed

Returns:

Transformed value

Return type:

Any

Example:

# Define condition and transformation functions
condition = lambda v: v == old
transform = lambda v: new

# Usage example
attribute_value = element.RelatedElements
print(old in attribute_value, new in attribute_value) # True, False

result = element.walk(condition, transform, element.RelatedElements)
print(old in attribute_value, new in attribute_value) # False, True
static wrap_value(v, file)
property file
wrapped_data: ifcopenshell.ifcopenshell_wrapper.entity_instance
class ifcopenshell.geom.file(f: ifcopenshell.ifcopenshell_wrapper.file | None = None, schema: str | None = None, schema_version: tuple[int, int, int, int] | None = None)

Base class for containing IFC files.

Class has instance methods for filtering by element Id, Type, etc. Instantiated objects can be subscripted by Id or Guid

Example:

model = ifcopenshell.open(file_path)
products = model.by_type("IfcProduct")
print(products[0].id(), products[0].GlobalId) # 122 2XQ$n5SLP5MBLyL442paFx
print(products[0] == model[122] == model["2XQ$n5SLP5MBLyL442paFx"]) # True

Create a new blank IFC model

This IFC model does not have any entities in it yet. See the create_entity function for how to create new entities. All data is stored in memory. If you wish to write the IFC model to disk, see the write function.

Parameters:
  • f – The underlying IfcOpenShell file object to be wrapped. This is an internal implementation detail and should generally be left as None by users.

  • schema (string) – Which IFC schema to use, chosen from “IFC2X3”, “IFC4”, or “IFC4X3”. These refer to the ISO approved versions of IFC. Defaults to “IFC4” if not specified, which is currently recommended for all new projects.

  • schema_version (tuple[int, int, int, int]) – If you want to specify an exact version of IFC that may not be an ISO approved version, use this argument instead of schema. IFC versions on technical.buildingsmart.org are described using 4 integers representing the major, minor, addendum, and corrigendum number. For example, (4, 0, 2, 1) refers to IFC4 ADD2 TC1, which is the official version approved by ISO when people refer to “IFC4”. Generally you should not use this argument unless you are testing non-ISO IFC releases.

Example:

# Create a new IFC4 model, create a wall, then save it to an IFC-SPF file.
model = ifcopenshell.file()
model.create_entity("IfcWall")
model.write("/path/to/model.ifc")

# Create a new IFC4X3 model
model = ifcopenshell.file(schema="IFC4X3")

# A poweruser testing out a particular version of IFC4X3
model = ifcopenshell.file(schema_version=(4, 3, 0, 1))
add(inst: ifcopenshell.entity_instance, _id: int = None) ifcopenshell.entity_instance

Adds an entity including any dependent entities to an IFC file. If the entity already exists, it is not re-added. Existence of entity is checked by it’s .identity().

Parameters:

inst (ifcopenshell.entity_instance) – The entity instance to add

Returns:

An ifcopenshell.entity_instance

Return type:

ifcopenshell.entity_instance

batch()

Low-level mechanism to speed up deletion of large subgraphs

begin_transaction() None
by_guid(guid: str) ifcopenshell.entity_instance

Return an IFC entity instance filtered by IFC GUID.

Parameters:

guid (string) – GlobalId value in 22-character encoded form

Raises:

RuntimeError – If guid is not found.

Returns:

An ifcopenshell.entity_instance

Return type:

ifcopenshell.entity_instance

by_id(id: int) ifcopenshell.entity_instance

Return an IFC entity instance filtered by IFC ID.

Parameters:

id (int) – STEP numerical identifier

Raises:

RuntimeError – If id is not found.

Returns:

An ifcopenshell.entity_instance

Return type:

ifcopenshell.entity_instance

by_type(type: str, include_subtypes=True) list[ifcopenshell.entity_instance]

Return IFC objects filtered by IFC Type and wrapped with the entity_instance class.

If an IFC type class has subclasses, all entities of those subclasses are also returned.

Parameters:
  • type (string) – The case insensitive type of IFC class to return.

  • include_subtypes (bool) – Whether or not to return subtypes of the IFC class

Raises:

RuntimeError – If type is not found in IFC schema.

Returns:

A list of ifcopenshell.entity_instance objects

Return type:

list[ifcopenshell.entity_instance]

create_entity(type: str, *args, **kwargs) ifcopenshell.entity_instance

Create a new IFC entity in the file.

You can also use dynamic methods similar to ifc_file.createIfcWall(…) to create IFC entities. They work exactly the same as if you would do ifc_file.create_entity(“IfcWall”, …) but the resulting typing is not as accurate as for create_entity due to a dynamic nature of those methods.

Parameters:
  • type (string) – Case insensitive name of the IFC class

  • args – The positional arguments of the IFC class

  • kwargs – The keyword arguments of the IFC class

Returns:

An entity instance

Return type:

ifcopenshell.entity_instance

Example:

f = ifcopenshell.file()
f.create_entity("IfcPerson")
# >>> #1=IfcPerson($,$,$,$,$,$,$,$)
f.create_entity("IfcPerson", "Foobar")
# >>> #2=IfcPerson('Foobar',$,$,$,$,$,$,$)
f.create_entity("IfcPerson", Identification="Foobar")
# >>> #3=IfcPerson('Foobar',$,$,$,$,$,$,$)
discard_transaction() None
end_transaction() None
static from_pointer(v) file
static from_string(s: str) file
get_inverse(inst: ifcopenshell.entity_instance, allow_duplicate: bool = False, with_attribute_indices: bool = False) list[ifcopenshell.entity_instance]

Return a list of entities that reference this entity

Warning: this is a slow function, especially when there is a large number of inverses (such as for a shared owner history). If you are only interested in the total number of inverses (typically 0, 1, or N), consider using get_total_inverses().

Parameters:
  • inst (ifcopenshell.entity_instance) – The entity instance to get inverse relationships

  • allow_duplicate – Returns a list when True, set when False

  • with_attribute_indices – Returns pairs of <i, idx> where i[idx] is inst or contains inst. Requires allow_duplicate=True

Returns:

A list of ifcopenshell.entity_instance objects

Return type:

list[ifcopenshell.entity_instance]

get_total_inverses(inst: ifcopenshell.entity_instance) int

Returns the number of entities that reference this entity

This is equivalent to len(model.get_inverse(element)), but significantly faster.

Parameters:

inst (ifcopenshell.entity_instance) – The entity instance to get inverse relationships

Returns:

The total number of references

Return type:

int

redo() None
remove(inst: ifcopenshell.entity_instance) None

Deletes an IFC object in the file.

Attribute values in other entity instances that reference the deleted object will be set to null. In the case of a list or set of references, the reference to the deleted will be removed from the aggregate.

Parameters:

inst (ifcopenshell.entity_instance) – The entity instance to delete

Return type:

None

set_history_size(size: int) None
traverse(inst: ifcopenshell.entity_instance, max_levels=None, breadth_first=False) list[ifcopenshell.entity_instance]

Get a list of all referenced instances for a particular instance including itself

Parameters:
  • inst (ifcopenshell.entity_instance) – The entity instance to get all sub instances

  • max_levels (bool) – How far deep to recursively fetch sub instances. None or -1 means infinite.

  • breadth_first – Whether to use breadth-first search, the default is depth-first.

Returns:

A list of ifcopenshell.entity_instance objects

Return type:

list[ifcopenshell.entity_instance]

unbatch()

Low-level mechanism to speed up deletion of large subgraphs

undo() None
write(path: os.PathLike | str, format: str | None = None, zipped: bool = False) None

Write ifc model to file.

:param format: Force use of a specific format. Guessed from file name

if None. Supported formats : .ifc, .ifcXML, .ifcZIP (equivalent to format=”.ifc” with zipped=True) For zipped .ifcXML use format=”.ifcXML” with zipped=True

:param zipped: zip the file after it is written :type zipped: bool

Example:

model.write("path/to/model.ifc")
model.write("path/to/model.ifcXML")
model.write("path/to/model.ifcZIP")
model.write("path/to/model.ifcZIP", format=".ifcXML", zipped=True)
model.write("path/to/model.anyextension", format=".ifcXML")
future = []
history = []
history_size = 64
property schema: Literal['IFC2X3', 'IFC4', 'IFC4X3']

General IFC schema version: IFC2X3, IFC4, IFC4X3.

property schema_identifier: str

Full IFC schema version: IFC2X3_TC1, IFC4_ADD2, IFC4X3_ADD2, etc.

property schema_version: tuple[int, int, int, int]

Numeric representation of the full IFC schema version.

E.g. IFC4X3_ADD2 is represented as (4, 3, 2, 0).

transaction: Transaction | None = None
wrapped_data: ifcopenshell.ifcopenshell_wrapper.file
class ifcopenshell.geom.iterator(settings: iterator.__init__.settings, file_or_filename: ifcopenshell.file.file | str, num_threads: int = 1, include: list[ifcopenshell.entity_instance.entity_instance] | list[str] | None = None, exclude: list[ifcopenshell.entity_instance.entity_instance] | list[str] | None = None, geometry_library: GEOMETRY_LIBRARY = 'opencascade')

Bases: ifcopenshell.ifcopenshell_wrapper.Iterator

settings
class ifcopenshell.geom.missing_setting
class ifcopenshell.geom.serializer_settings(**kwargs)

Bases: settings_mixin, ifcopenshell.ifcopenshell_wrapper.SerializerSettings

Pythonic interface mixin to the settings modules and to provide an additional setting to enable pythonOCC when available

class ifcopenshell.geom.serializers
static obj(out_filename: str | serializers, mtl_filename: str | serializers, geometry_settings: serializers.obj.settings, settings: serializer_settings) ifcopenshell.ifcopenshell_wrapper.WaveFrontOBJSerializer
static svg(out_filename: str | serializers, geometry_settings: serializers.svg.settings, settings: serializer_settings) ifcopenshell.ifcopenshell_wrapper.SvgSerializer
buffer
xml
class ifcopenshell.geom.settings(**kwargs)

Bases: settings_mixin, ifcopenshell.ifcopenshell_wrapper.Settings

Pythonic interface mixin to the settings modules and to provide an additional setting to enable pythonOCC when available

use_python_opencascade = False
class ifcopenshell.geom.settings_mixin(**kwargs)

Pythonic interface mixin to the settings modules and to provide an additional setting to enable pythonOCC when available

get(k: SETTING) Any
get(k: SERIALIZER_SETTING) Any

Return value of the setting named k.

Raises:

RuntimeError – If there is no setting with name k.

static name(k: str) SETTING | SERIALIZER_SETTING
static rname(k: SETTING | SERIALIZER_SETTING) str
set(k: SETTING, v: Any) None
set(k: SERIALIZER_SETTING, v: Any) None

Set value of the setting named k to v.

Raises:

RuntimeError – If there is no setting with name k.

setting_names() tuple[SETTING, Ellipsis]
setting_names() tuple[SERIALIZER_SETTING, Ellipsis]
class ifcopenshell.geom.tree(file: tree.__init__.file | None = None, settings: tree.__init__.settings | None = None)

Bases: ifcopenshell.ifcopenshell_wrapper.tree

add_file(file: tree.add_file.file, settings: tree.add_file.settings) None
add_iterator(iterator: tree.add_iterator.iterator) None
clash_clearance_many(set_a, set_b, clearance=0.05, check_all=False)
clash_collision_many(set_a, set_b, allow_touching=False)
clash_intersection_many(set_a, set_b, tolerance=0.002, check_all=True)
select(value: ifcopenshell.entity_instance.entity_instance | ifcopenshell.ifcopenshell_wrapper.BRepElement | tuple[float, float, float] | OCC.Core.TopoDS.TopoDS_Shape, **kwargs) list[ifcopenshell.entity_instance.entity_instance]
select_box(value, **kwargs) list[ifcopenshell.entity_instance.entity_instance]
args
ifcopenshell.geom.consume_iterator(it, with_progress=False)
ifcopenshell.geom.create_shape(settings: create_shape.settings, inst: ifcopenshell.entity_instance.entity_instance, repr: ifcopenshell.entity_instance.entity_instance | None = None, geometry_library: GEOMETRY_LIBRARY = 'opencascade') ShapeType | ShapeElementType | ifcopenshell.ifcopenshell_wrapper.Transformation | ifcopenshell.geom.occ_utils.shape_tuple | OCC.Core.TopoDS.TopoDS_Shape

Return a geometric representation from STEP-based IFCREPRESENTATIONSHAPE or Return an OpenCASCADE BRep if settings.USE_PYTHON_OPENCASCADE == True

Note that in Python, you must store a reference to the element returned by this function to prevent garbage collection when you access its children. See #1124.

Raises:

RuntimeError – If failed to process shape. You can turn detailed logging to get more details.

Returns:

  • inst is IfcProduct and repr provided / None -> ShapeElementType

  • inst is IfcRepresentation and repr is None -> ShapeType

  • inst is IfcRepresentationItem and repr is None -> ShapeType

  • inst is IfcProfileDef and repr is None -> ShapeType

  • inst is IfcPlacement / IfcObjectPlacement -> Transformation

  • inst is IfcTypeProduct and repr is None -> None

  • inst is IfcTypeProduct and repr is provided -> RuntimeError

(for IfcTypeProducts provide just IfcRepresentation as inst).

If ‘use-python-opencascade’ is enabled in settings then

  • instead of ShapeElementType it returns shape_tuple,

  • instead of ShapeType it returns TopoDS.TopoDS_Shape.

Example:

settings = ifcopenshell.geom.settings()
settings.set(settings.USE_PYTHON_OPENCASCADE, True)

ifc_file = ifcopenshell.open(file_path)
products = ifc_file.by_type("IfcProduct")

for i, product in enumerate(products):
    if product.Representation is not None:
        try:
            created_shape = geom.create_shape(settings, inst=product)
            shape = created_shape.geometry # see #1124
            shape_gpXYZ = shape.Location().Transformation().TranslationPart() # These are methods of the TopoDS_Shape class from pythonOCC
            print(shape_gpXYZ.X(), shape_gpXYZ.Y(), shape_gpXYZ.Z()) # These are methods of the gpXYZ class from pythonOCC
        except:
            print("Shape creation failed")
ifcopenshell.geom.iterate(settings, file_or_filename, num_threads=1, include=None, exclude=None, with_progress=False, cache=None, geometry_library: GEOMETRY_LIBRARY = 'opencascade')
ifcopenshell.geom.make_shape_function(fn)
ifcopenshell.geom.transform_string(v: str | serializers.buffer) serializers.buffer
ifcopenshell.geom.wrap_shape_creation(settings, shape)
ifcopenshell.geom.GEOMETRY_LIBRARY
ifcopenshell.geom.SERIALIZER_SETTING
ifcopenshell.geom.SETTING
ifcopenshell.geom.ShapeElementType
ifcopenshell.geom.ShapeType
ifcopenshell.geom.T
ifcopenshell.geom.has_occ
ifcopenshell.geom.serialise
ifcopenshell.geom.tesselate