Skip to main content

03 - BIM and IFC Files: Model Structure and Clash Detection

What an IFC file looks like and how to find clashes between BIM model elements without comparing every pair, with Python listings that were run.

What do you think about this article?

03 - BIM and IFC Files: Model Structure and Clash Detection
PropTechPhoto:Ruben BoekelooPexels

At a Glance

What an IFC file looks like and how to find clashes between BIM model elements without comparing every pair, with Python listings that were run.

A BIM model is a database of objects, not a 3D drawing

Anyone arriving at BIM as a developer tends to see it as a 3D format, a cousin of video game models. It is the misunderstanding that costs the most. A BIM model (building information modeling) is a set of objects with meaning: this is a wall, it contains these doors, it sits on this floor, it has this material, it is the same thing the bill of quantities calls "external wall type B". Geometry is one of the object's properties, and not the most important for someone who develops software: the difference between a viewer and a BIM platform lies entirely in the way those objects are read and queried.

Exchange between different programs happens in a neutral format, IFC (Industry Foundation Classes), standardised by ISO 16739-1 (the second edition is from 2024). In this article we open the format and read a fragment by hand, then tackle the first serious computational problem a BIM software must solve, the search for conflicts between elements (clash detection), and show why the naive algorithm does not hold up on a real building. Both listings were run with Python 3.14.

What an IFC file looks like: numbered entities that point to each other

The most common form of IFC file is a text that follows the STEP syntax (ISO 10303-21, "clear text encoding of the exchange structure"). Each line declares an entity with a number: #10=IFCWALL(...) is entity 10, a wall. Entities refer to each other by number, and the relationship "this wall is on this floor" is itself an entity (IFCRELCONTAINEDINSPATIALSTRUCTURE) that lists the contained elements and the container. That is why an IFC file is read as a graph, not as a list.

Reading an IFC fragment in STEP syntax: type and floor of each element
import re
from collections import Counter

# Didactic fragment in STEP syntax (ISO 10303-21). It is NOT a complete IFC file.
IFC = """ISO-10303-21;
DATA;
#1=IFCBUILDINGSTOREY('2Ab01',$,'Piano terra',$,$,$,$,$,.ELEMENT.,0.);
#2=IFCBUILDINGSTOREY('2Ab02',$,'Piano primo',$,$,$,$,$,.ELEMENT.,3.2);
#10=IFCWALL('3Cd10',$,'Muro-N-01',$,$,$,$,'W10');
#11=IFCWALL('3Cd11',$,'Muro-N-02, spalla',$,$,$,$,'W11');
#12=IFCWALL('3Cd12',$,'Muro-P1-01',$,$,$,$,'W12');
#20=IFCDOOR('4Ef20',$,'Porta ingresso',$,$,$,$,'D20',2.1,0.9);
#30=IFCRELCONTAINEDINSPATIALSTRUCTURE('5Gh30',$,$,$,(#10,#11,#20),#1);
#31=IFCRELCONTAINEDINSPATIALSTRUCTURE('5Gh31',$,$,$,(#12),#2);
ENDSEC;
END-ISO-10303-21;
"""


def argomenti(testo):
    """Splits the arguments at the outermost level: respects parentheses and quotes."""
    out, cur, depth, apice = [], "", 0, False
    for c in testo:
        if c == "'":
            apice = not apice
        if not apice:
            if c == "(":
                depth += 1
            elif c == ")":
                depth -= 1
            elif c == "," and depth == 0:
                out.append(cur)
                cur = ""
                continue
        cur += c
    out.append(cur)
    return out


entita = {}
for m in re.finditer(r"#(\d+)\s*=\s*(\w+)\((.*?)\);", IFC, re.S):
    entita[int(m.group(1))] = (m.group(2), argomenti(m.group(3)))

print("tipi:", dict(Counter(t for t, _ in entita.values())))

for _, (tipo, a) in entita.items():
    if tipo == "IFCRELCONTAINEDINSPATIALSTRUCTURE":
        piano = entita[int(a[5].strip("#"))][1][2].strip("'")
        for rif in a[4].strip("()").split(","):
            nome = entita[int(rif.strip().strip("#"))][1][2].strip("'")
            print(f"{piano}: {nome}")

# Output:
# tipi: {'IFCBUILDINGSTOREY': 2, 'IFCWALL': 3, 'IFCDOOR': 1, 'IFCRELCONTAINEDINSPATIALSTRUCTURE': 2}
# Piano terra: Muro-N-01
# Piano terra: Muro-N-02, spalla
# Piano terra: Porta ingresso
# Piano primo: Muro-P1-01

The listing is a minimal reader, written to see the format and not to use in production. The fragment is didactic: its attributes are fewer than those the IFC schema provides for each entity, and a real file has tens of thousands of them. The function that matters is argomenti: it splits the arguments of an entity at the top-level commas, ignoring those inside parentheses and quotes. Without this precaution the wall called "Muro-N-02, spalla" would be split into two arguments and all the following indexes would slip by one. The output confirms it: the comma in the name survives, and each element is assigned to the right floor by following the numbers (relationship #30 points to #1, the ground floor).

For a real file, do not write a reader: use a library. IfcOpenShell is the standard one in Python, and its documentation shows the essential use, ifcopenshell.open to open the file and model.by_type('IfcWall') to get the objects of a type. The advantage is not only convenience: the library knows the schema, resolves references, handles IFC versions and computes geometry, that is, the things our twenty-line reader does not do. This listing does not use it because IfcOpenShell is not installed on the machine where the listings were run, and we prefer to show code that really runs over code we could not launch.

Clash detection: why comparing everything with everything does not work

A clash is a point where two elements occupy the same space: an air duct crossing a beam, a plumbing line running through a pillar. Finding them at design time costs a change to the drawing; finding them on site costs a demolition. The precise geometric test (mesh against mesh) is slow, so you proceed in two phases: a broad phase that quickly discards pairs that are surely far apart using the boxes that enclose the elements (AABB, axis-aligned bounding box), and a narrow phase that checks the true geometry only on the remaining pairs.

Broad phase: comparing all pairs versus sorting on the x axis
import random
from itertools import combinations

random.seed(11)  # same elements on every run


def scatola(i, tipo):
    x, y = random.uniform(0, 400), random.uniform(0, 400)
    dx, dy, dz = {"trave": (6.0, 0.3, 0.5), "condotta": (1.0, 0.4, 0.4), "pilastro": (0.4, 0.4, 3.0)}[tipo]
    z = random.uniform(0, 12)
    return (i, tipo, (x, y, z), (x + dx, y + dy, z + dz))  # minimum and maximum (AABB)


elementi = [scatola(i, random.choice(["trave", "condotta", "pilastro"])) for i in range(3000)]


def penetrazione(a, b):
    """By how much the boxes overlap on the three axes (negative = separate)."""
    return min(min(a[3][k], b[3][k]) - max(a[2][k], b[2][k]) for k in range(3))


def clash_naive(el, tolleranza):
    confronti = 0
    trovati = []
    for a, b in combinations(el, 2):
        confronti += 1
        if penetrazione(a, b) > tolleranza:
            trovati.append((a[0], b[0]))
    return trovati, confronti


def clash_sweep(el, tolleranza):
    """Sorts by minimum x and compares only those that overlap on the x axis."""
    ordinati = sorted(el, key=lambda e: e[2][0])
    confronti, trovati = 0, []
    for i, a in enumerate(ordinati):
        for b in ordinati[i + 1:]:
            if b[2][0] > a[3][0]:
                break
            confronti += 1
            if penetrazione(a, b) > tolleranza:
                trovati.append(tuple(sorted((a[0], b[0]))))
    return trovati, confronti


for tol in (0.0, 0.05):
    n, cn = clash_naive(elementi, tol)
    s, cs = clash_sweep(elementi, tol)
    print(f"tolleranza {tol:4.2f} m: conflitti naive={len(n)} sweep={len(s)} uguali={sorted(n) == sorted(s)}")
print(f"confronti: naive={cn} sweep={cs}")

# Output:
# tolleranza 0.00 m: conflitti naive=13 sweep=13 uguali=True
# tolleranza 0.05 m: conflitti naive=9 sweep=9 uguali=True
# confronti: naive=4498500 sweep=54834

The listing generates 3,000 elements with a fixed seed (beams, ducts and pillars scattered over an area of 400 by 400 metres, just to have data) and looks for clashes in two ways. The naive approach, clash_naive, compares every pair: with 3,000 elements that is 4,498,500 comparisons, and it grows with the square of the number of elements. The sweep approach, clash_sweep, sorts the elements by minimum x coordinate and, for each one, compares only with those that start before its interval on the x axis ends: it breaks the loop with break as soon as it finds one that starts later. The output shows that the two methods find exactly the same clashes (uguali=True) with 54,834 comparisons instead of 4,498,500.

The tolleranza parameter is the design decision that weighs the most. With zero tolerance the listing finds 13 clashes, with 5 centimetres it finds 9: the 4 that disappear are pairs of boxes that overlap by less than 5 centimetres, the kind of "clash" a designer does not want to see in a report. A tolerance that is too low fills the report with false alarms and people stop reading it; one that is too high hides a real clash. The value is negotiated with the designers and depends on the type of pair (a duct brushing a false ceiling is not a pillar cut through). Remember that boxes overestimate the elements: a diagonal beam has a box much larger than its real footprint, so the narrow phase must confirm every pair flagged by the broad phase.

The sweep has a limit too: if the elements are all aligned on the x axis (a long, narrow corridor) the sorting discards almost nothing and you get back close to the naive case. Real software uses spatial structures (box trees, grids) that sort on all axes. For your case, measure the reduction in comparisons on your model before choosing.

Where the rest of the series connects

The BIM model describes the building as designed; the digital twin updates it with what happens inside, and the hook is the sensors: the identifier of the IFC object (the GlobalId in the first argument of every entity) is the key to associate a temperature reading with the right room. How to bring those readings from the building to the platform is in the article on smart building IoT. The section on maintenance, which uses that association to decide when to intervene, is in the article on property management with agents; for the way a building's objects enter a catalogue of listings, go back to the platform architecture. To find where an element of the model sits, as a database query, see geospatial search with PostGIS. To show a space to a visitor with a panoramic photo instead of a model, see virtual tours.

What you can do now

You can read an IFC file for what it is, a graph of numbered entities with relationships as entities of their own; you know why a reader must respect commas and quotes, and when to move to IfcOpenShell. You can set up a two-phase clash search and you have seen, with the numbers from the run, what you gain by not comparing everything with everything and what the tolerance decides. What we did not show, because it needs a geometry library that was not available, is the narrow phase and the web viewer: these are jobs for which it is best to start from IfcOpenShell and from the documentation of your 3D engine.

In this series, the previous article is Property Valuation with ML: How to Measure the Error.

Sources

The two listings were run with Python 3.14 on 2026-11-12; the outputs shown are the real ones, and the number of clashes and comparisons depends on the seed (11) declared in the listing. The IfcOpenShell example was not run.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects