Ejemplo n.º 1
0
 def __init__(self, fn, gf=None, wf=None, group_lines=True):
     self.f = ifcopenshell.open(fn)
     self.group_lines = group_lines
     if gf:
         self.gf = ifcopenshell.open(gf)
         self.calc_grid_pts()
     if wf:
         self.wf = ifcopenshell.open(wf)
         self.calc_opening_centers()
Ejemplo n.º 2
0
    def process_clash_set(self, clash_set):
        for ab in ["a", "b"]:
            self.settings.logger.info(f"Creating collision manager {ab} ...")
            clash_set[f"{ab}_cm"] = collision.CollisionManager()
            self.settings.logger.info(f"Loading files {ab} ...")
            for data in clash_set[ab]:
                data["ifc"] = ifcopenshell.open(data["file"])
                self.patch_ifc(data["ifc"])
                self.settings.logger.info(
                    f"Creating collision data for {ab} ...")
                if len(data["ifc"].by_type("IfcElement")) > 0:
                    self.add_collision_objects(data, clash_set[f"{ab}_cm"])

        if "b" in clash_set and clash_set["b"]:
            results = clash_set["a_cm"].in_collision_other(clash_set["b_cm"],
                                                           return_data=True)
        else:
            results = clash_set["a_cm"].in_collision_internal(return_data=True)

        if not results[0]:
            return

        tolerance = clash_set["tolerance"] if "tolerance" in clash_set else 0.01
        clash_set["clashes"] = {}

        for contact in results[1]:
            a_global_id, b_global_id = contact.names
            a = self.get_element(clash_set["a"], a_global_id)
            if "b" in clash_set and clash_set["b"]:
                b = self.get_element(clash_set["b"], b_global_id)
            else:
                b = self.get_element(clash_set["a"], b_global_id)
            if contact.raw.penetration_depth < tolerance:
                continue

            # fcl returns contact data for faces that aren't actually
            # penetrating, but just touching. If our tolerance is zero, then we
            # consider these as clashes and we move on. If our tolerance is not
            # zero, fcl has a strange behaviour where the penetration depth can
            # be a large number even though objects are just touching
            # https://github.com/flexible-collision-library/fcl/issues/503 In
            # this case, I don't trust the penetration depth and I run my own
            # triangle-triangle intersection test. Optimistically, this skips
            # the false positives. Conservatively, we let the user manually deal
            # with the false positives and we mark it as a clash.
            is_optimistic = True  # TODO: let user configure this

            if is_optimistic and tolerance != 0:
                # We'll now check if the contact data's two faces are actually
                # intersecting, using this brute force check:
                # https://stackoverflow.com/questions/7113344/find-whether-two-triangles-intersect-or-not
                # I'm not very good at this kind of code. If you know this stuff
                # please help rewrite this.

                # Get vertices of clashing tris
                p1 = self.global_data["meshes"][contact.names[0]].faces[
                    contact.index(contact.names[0])]
                p2 = self.global_data["meshes"][contact.names[1]].faces[
                    contact.index(contact.names[1])]
                m1 = self.global_data["matrices"][contact.names[0]]
                m2 = self.global_data["matrices"][contact.names[1]]
                v1 = []
                v2 = []

                for v in p1:
                    v1.append((m1 @ np.array([
                        *self.global_data["meshes"][
                            contact.names[0]].vertices[v], 1
                    ]))[0:3].round(2))
                for v in p2:
                    v2.append((m2 @ np.array([
                        *self.global_data["meshes"][
                            contact.names[1]].vertices[v], 1
                    ]))[0:3].round(2))

                tri1_x = 0
                tri2_x = 0
                tri1_x += 1 if self.intersect_line_triangle(
                    v1[0], v1[1], v2[0], v2[1], v2[2]) is not None else 0
                tri1_x += 1 if self.intersect_line_triangle(
                    v1[1], v1[2], v2[0], v2[1], v2[2]) is not None else 0
                tri1_x += 1 if self.intersect_line_triangle(
                    v1[2], v1[0], v2[0], v2[1], v2[2]) is not None else 0

                tri2_x += 1 if self.intersect_line_triangle(
                    v2[0], v2[1], v1[0], v1[1], v1[2]) is not None else 0
                tri2_x += 1 if self.intersect_line_triangle(
                    v2[1], v2[2], v1[0], v1[1], v1[2]) is not None else 0
                tri2_x += 1 if self.intersect_line_triangle(
                    v2[2], v2[0], v1[0], v1[1], v1[2]) is not None else 0
                intersections = [tri1_x, tri2_x]
                if intersections == [0, 2] or intersections == [
                        2, 0
                ] or intersections == [1, 1]:
                    # This is a penetrating collision
                    pass
                else:
                    # This is probably two triangles which just touch
                    continue

            key = f"{a_global_id}-{b_global_id}"

            if (key in clash_set["clashes"]
                    and clash_set["clashes"][key]["penetration_depth"] >
                    contact.raw.penetration_depth):
                continue

            clash_set["clashes"][key] = {
                "a_global_id": a_global_id,
                "b_global_id": b_global_id,
                "a_ifc_class": a.is_a(),
                "b_ifc_class": b.is_a(),
                "a_name": a.Name,
                "b_name": b.Name,
                "normal": list(contact.raw.normal),
                "position": list(contact.raw.pos),
                "penetration_depth": contact.raw.penetration_depth,
            }
Ejemplo n.º 3
0
import ifcopenshell

file = ifcopenshell.open("180502.ifc")

project = file.by_type("IfcProject")[0]
print(project)

# IFCRelSpaceBoundary
boundary = file.by_type("IFCRelSpaceBoundary")
print(boundary)
for i in range(len(boundary)):
    print(boundary[i])

# IFCRelationship
relation = file.by_type("IFCRelationship")
print(relation)
for i in range(len(relation)):
    print(relation[i])

# IFCR한글로하면?
import unicodedata

from datetime import datetime
from collections import defaultdict
from lxml import etree as ET
from operator import itemgetter
from collections import OrderedDict
from itertools import combinations

fname = input('Give in absolute file path to IFC file:')

while fname.endswith('.ifc') == False:
    print ('The path you gave is not an IFC file.')
    fname = input('Give in file path to IFC file:')
    
ifcfile = ifcopenshell.open(fname)
products = ifcfile.by_type('IfcProduct')

project = ifcfile.by_type('IfcProject')
site = ifcfile.by_type('IfcSite')

head, tail = os.path.split(fname)
folder_name = 'sets_Navisworks_Manage_' + tail.replace('.ifc','') 

class GetIDMdata():
    def get_software(self):
        print ('get software')
        
        software_list = []
        
        for j in project:
Ejemplo n.º 5
0
 def load(self, fn):
     if fn in self.files: return
     f = ifcopenshell.open(fn)
     self.files[fn] = f
     for c in self.components:
         c.load_file(f, setting=self.settings)
Ejemplo n.º 6
0
def open(fn): return file(ifcopenshell.open(fn))

class query_unique(object): pass
Ejemplo n.º 7
0
def explore(filename=None):
    """explore([filename]): opens a dialog showing 
    the contents of an IFC file. If no filename is given, a dialog will
    pop up to choose a file."""
    
    p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch")
    DEBUG = p.GetBool("ifcDebug",False)
    
    try:
        import ifcopenshell
    except:
        FreeCAD.Console.PrintError("IfcOpenShell was not found on this system. IFC support is disabled\n")
        return
    
    if not filename:
        from PySide import QtGui
        filename = QtGui.QFileDialog.getOpenFileName(QtGui.qApp.activeWindow(),'IFC files','*.ifc')
        if filename:
            filename = filename[0]
        
    from PySide import QtCore,QtGui
    
    if isinstance(filename,unicode): 
        import sys #workaround since ifcopenshell currently can't handle unicode filenames
        filename = filename.encode(sys.getfilesystemencoding())
        
    if not os.path.exists(filename):
        print "File not found"
        return

    ifc = ifcopenshell.open(filename)
    tree = QtGui.QTreeWidget()
    tree.setColumnCount(3)
    tree.setWordWrap(True)
    tree.header().setDefaultSectionSize(60)
    tree.header().resizeSection(0,60)
    tree.header().resizeSection(1,30)
    tree.header().setStretchLastSection(True)
    tree.headerItem().setText(0, "ID")
    tree.headerItem().setText(1, "")
    tree.headerItem().setText(2, "Item and Properties")
    bold = QtGui.QFont()
    bold.setWeight(75)
    bold.setBold(True)
    
    entities =  ifc.by_type("IfcRoot")
    entities += ifc.by_type("IfcRepresentation")
    entities += ifc.by_type("IfcRepresentationItem")
    entities += ifc.by_type("IfcPlacement")
    entities = sorted(entities, key=lambda eid: eid.id())

    for entity in entities:
        item = QtGui.QTreeWidgetItem(tree)
        if hasattr(entity,"id"):
            item.setText(0,str(entity.id()))
            if entity.is_a() in ["IfcWall","IfcWallStandardCase"]:
                item.setIcon(1,QtGui.QIcon(":icons/Arch_Wall_Tree.svg"))
            elif entity.is_a() in ["IfcColumn","IfcColumnStandardCase","IfcBeam","IfcBeamStandardCase","IfcSlab","IfcFooting","IfcPile","IfcTendon"]:
                item.setIcon(1,QtGui.QIcon(":icons/Arch_Structure_Tree.svg"))
            elif entity.is_a() in ["IfcSite"]:
                item.setIcon(1,QtGui.QIcon(":icons/Arch_Site_Tree.svg"))
            elif entity.is_a() in ["IfcBuilding"]:
                item.setIcon(1,QtGui.QIcon(":icons/Arch_Building_Tree.svg"))
            elif entity.is_a() in ["IfcBuildingStorey"]:
                item.setIcon(1,QtGui.QIcon(":icons/Arch_Floor_Tree.svg"))
            elif entity.is_a() in ["IfcWindow","IfcWindowStandardCase","IfcDoor","IfcDoorStandardCase"]:
                item.setIcon(1,QtGui.QIcon(":icons/Arch_Window_Tree.svg"))
            elif entity.is_a() in ["IfcRoof"]:
                item.setIcon(1,QtGui.QIcon(":icons/Arch_Roof_Tree.svg"))
            elif entity.is_a() in ["IfcExtrudedAreaSolid","IfcClosedShell"]:
                item.setIcon(1,QtGui.QIcon(":icons/Tree_Part.svg"))
            elif entity.is_a() in ["IfcFace"]:
                item.setIcon(1,QtGui.QIcon(":icons/Draft_SwitchMode.svg"))
            elif entity.is_a() in ["IfcArbitraryClosedProfileDef","IfcPolyloop"]:
                item.setIcon(1,QtGui.QIcon(":icons/Draft_Draft.svg"))
            item.setText(2,str(entity.is_a()))
            item.setFont(2,bold);
            
            i = 0
            while True:
                try:
                    argname = entity.attribute_name(i)
                except:
                    break
                else:
                    try:
                        argvalue = getattr(entity,argname)
                    except:
                        print "Error in entity ",entity
                        break
                    else:
                        if not argname in ["Id", "GlobalId"]:
                            if isinstance(argvalue,ifcopenshell.entity_instance):
                                t = "Entity #" + str(argvalue.id()) + ": " + str(argvalue.is_a())
                            elif isinstance(argvalue,list):
                                t = ""
                            else:
                                t = str(argvalue)
                            t = "    " + str(argname) + " : " + str(t)
                            item = QtGui.QTreeWidgetItem(tree)
                            item.setText(2,str(t))
                            if isinstance(argvalue,list):
                                for argitem in argvalue:
                                    if isinstance(argitem,ifcopenshell.entity_instance):
                                        t = "Entity #" + str(argitem.id()) + ": " + str(argitem.is_a()) 
                                    else:
                                        t = argitem
                                    t = "        " + str(t)
                                    item = QtGui.QTreeWidgetItem(tree)
                                    item.setText(2,str(t))
                    i += 1
                    
    d = QtGui.QDialog()
    d.setObjectName("IfcExplorer")
    d.setWindowTitle("Ifc Explorer")
    d.resize(640, 480)
    layout = QtGui.QVBoxLayout(d)
    layout.addWidget(tree)

    d.exec_()
    return
Ejemplo n.º 8
0
def insert(filename,docname,skip=[],only=[],root=None):
    """insert(filename,docname,skip=[],only=[],root=None): imports the contents of an IFC file.
    skip can contain a list of ids of objects to be skipped, only can restrict the import to
    certain object ids (will also get their children) and root can be used to
    import only the derivates of a certain element type (default = ifcProduct)."""
    
    p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch")
    DEBUG = p.GetBool("ifcDebug",False)
    PREFIX_NUMBERS = p.GetBool("ifcPrefixNumbers",False)
    SKIP = p.GetString("ifcSkip","").split(",")
    SEPARATE_OPENINGS = p.GetBool("ifcSeparateOpenings",False)
    ROOT_ELEMENT = p.GetString("ifcRootElement","IfcProduct")
    if root:
        ROOT_ELEMENT = root
    MERGE_MODE = p.GetInt("ifcImportMode",0)
    if MERGE_MODE > 0:
        SEPARATE_OPENINGS = False
    READ_COLORS = p.GetBool("ifcReadColors",True)
    if not SEPARATE_OPENINGS:
        SKIP.append("IfcOpeningElement")
    
    try:
        import ifcopenshell
    except:
        FreeCAD.Console.PrintError("IfcOpenShell was not found on this system. IFC support is disabled\n")
        return

    if DEBUG: print "Opening ",filename,"...",
    try:
        doc = FreeCAD.getDocument(docname)
    except:
        doc = FreeCAD.newDocument(docname)
    FreeCAD.ActiveDocument = doc
    
    if DEBUG: print "done."
    
    global ifcfile # keeping global for debugging purposes
    if isinstance(filename,unicode): 
        import sys #workaround since ifcopenshell currently can't handle unicode filenames
        filename = filename.encode(sys.getfilesystemencoding())
    ifcfile = ifcopenshell.open(filename)
    from ifcopenshell import geom
    settings = ifcopenshell.geom.settings()
    settings.set(settings.USE_BREP_DATA,True)
    settings.set(settings.SEW_SHELLS,True)
    settings.set(settings.USE_WORLD_COORDS,True)
    if SEPARATE_OPENINGS: 
        settings.set(settings.DISABLE_OPENING_SUBTRACTIONS,True)
    sites = ifcfile.by_type("IfcSite")
    buildings = ifcfile.by_type("IfcBuilding")
    floors = ifcfile.by_type("IfcBuildingStorey")
    products = ifcfile.by_type(ROOT_ELEMENT)
    openings = ifcfile.by_type("IfcOpeningElement")
    annotations = ifcfile.by_type("IfcAnnotation")
    
    if DEBUG: print "Building relationships table...",

    # building relations tables
    objects = {} # { id:object, ... }
    additions = {} # { host:[child,...], ... }
    subtractions = [] # [ [opening,host], ... ]
    properties = {} # { host:[property, ...], ... }
    colors = {} # { id:(r,g,b) }
    shapes = {} # { id:shaoe } only used for merge mode
    for r in ifcfile.by_type("IfcRelContainedInSpatialStructure"):
        additions.setdefault(r.RelatingStructure.id(),[]).extend([e.id() for e in r.RelatedElements])
    for r in ifcfile.by_type("IfcRelAggregates"):
        additions.setdefault(r.RelatingObject.id(),[]).extend([e.id() for e in r.RelatedObjects])
    for r in ifcfile.by_type("IfcRelVoidsElement"):
        subtractions.append([r.RelatedOpeningElement.id(), r.RelatingBuildingElement.id()])
    for r in ifcfile.by_type("IfcRelDefinesByProperties"):
        for obj in r.RelatedObjects:
            if r.RelatingPropertyDefinition.is_a("IfcPropertySet"):
                properties.setdefault(obj.id(),[]).extend([e.id() for e in r.RelatingPropertyDefinition.HasProperties])
    if READ_COLORS:
        for r in ifcfile.by_type("IfcStyledItem"):
            if r.Item and r.Styles[0].is_a("IfcPresentationStyleAssignment"):
                if r.Styles[0].Styles[0].is_a("IfcSurfaceStyle"):
                    if r.Styles[0].Styles[0].Styles[0].is_a("IfcSurfaceStyleRendering"):
                        if r.Styles[0].Styles[0].Styles[0].SurfaceColour:
                            c = r.Styles[0].Styles[0].Styles[0].SurfaceColour
                            for p in ifcfile.by_type("IfcProduct"):
                                if p.Representation:
                                    for it in p.Representation.Representations:
                                        if it.Items:
                                            if it.Items[0].id() == r.Item.id():
                                                colors[p.id()] = (c.Red,c.Green,c.Blue)
                                            elif it.Items[0].is_a("IfcBooleanResult"):
                                                if (it.Items[0].FirstOperand.id() == r.Item.id()):
                                                    colors[p.id()] = (c.Red,c.Green,c.Blue)
    if only: # only import a list of IDs and their children
        ids = []
        while only:
            currentid = only.pop()
            ids.append(currentid)
            if currentid in additions.keys():
                only.extend(additions[currentid])
        products = [ifcfile[currentid] for currentid in ids]
                    
    if DEBUG: print "done."
        
    count = 0
    from FreeCAD import Base
    progressbar = Base.ProgressIndicator()
    progressbar.start("Importing IFC objects...",len(products))

    # products
    for product in products:
                
        pid = product.id()
        guid = product.GlobalId
        ptype = product.is_a()
        if DEBUG: print count,"/",len(products)," creating object ",pid," : ",ptype,
        name = product.Name or str(ptype[3:])
        if PREFIX_NUMBERS: name = "ID" + str(pid) + " " + name
        obj = None
        baseobj = None
        brep = None

        if pid in skip: # user given id skip list
            if DEBUG: print " skipped."
            continue
        if ptype in SKIP: # preferences-set type skip list
            if DEBUG: print " skipped."
            continue
            
        try:
            cr = ifcopenshell.geom.create_shape(settings,product)
            brep = cr.geometry.brep_data
        except:
            pass # IfcOpenShell will yield an error if a given product has no shape, but we don't care
            
        if brep:
            if DEBUG: print " ",str(len(brep)/1000),"k ",
            
            shape = Part.Shape()
            shape.importBrepFromString(brep)
            
            shape.scale(1000.0) # IfcOpenShell always outputs in meters

            if not shape.isNull():
                if MERGE_MODE > 0:
                    if ptype == "IfcSpace": # do not add spaces to compounds
                        if DEBUG: print "skipping space ",pid
                    else:
                        shapes[pid] = shape
                        if DEBUG: print shape.Solids
                        baseobj = shape
                else:
                    baseobj = FreeCAD.ActiveDocument.addObject("Part::Feature",name+"_body")
                    baseobj.Shape = shape
            else:
                if DEBUG: print  "null shape ",
            if not shape.isValid():
                if DEBUG: print "invalid shape. Skipping"
                continue
                
        else:
            if DEBUG: print " no brep "
            
        if MERGE_MODE == 0:
            
            # full Arch objects
            for freecadtype,ifctypes in typesmap.items():
                if ptype in ifctypes:
                    obj = getattr(Arch,"make"+freecadtype)(baseobj=baseobj,name=name)
                    obj.Label = name
                    # setting role
                    try:
                        r = ptype[3:]
                        tr = dict((v,k) for k, v in translationtable.iteritems())
                        if r in tr.keys():
                            r = tr[r]
                        # remove the "StandardCase"
                        if "StandardCase" in r:
                            r = r[:-12]
                        obj.Role = r
                    except:
                        pass
                    # setting uid
                    if hasattr(obj,"IfcAttributes"):
                        a = obj.IfcAttributes
                        a["IfcUID"] = str(guid)
                        obj.IfcAttributes = a
                    break
            if not obj:
                obj = baseobj
            if obj:
                sols = str(baseobj.Shape.Solids) if hasattr(baseobj,"Shape") else "[]"
                if DEBUG: print sols
                objects[pid] = obj
                        
        elif MERGE_MODE == 1:
            
            # non-parametric Arch objects
            if ptype in ["IfcSite","IfcBuilding","IfcBuildingStorey"]:
                for freecadtype,ifctypes in typesmap.items():
                    if ptype in ifctypes:
                        obj = getattr(Arch,"make"+freecadtype)(baseobj=None,name=name)
                        obj.Label = name
                        objects[pid] = obj
            elif baseobj:
                obj = Arch.makeComponent(baseobj,name=name)
                obj.Label = name
                objects[pid] = obj
                
        elif MERGE_MODE == 2:
            
            # Part shapes
            if ptype in ["IfcSite","IfcBuilding","IfcBuildingStorey"]:
                for freecadtype,ifctypes in typesmap.items():
                    if ptype in ifctypes:
                        obj = getattr(Arch,"make"+freecadtype)(baseobj=None,name=name)
                        obj.Label = name
                        objects[pid] = obj
            elif baseobj:
                obj = FreeCAD.ActiveDocument.addObject("Part::Feature",name)
                obj.Label = name
                obj.Shape = shape

                
        if obj:
            
            # properties
            if pid in properties:
                if hasattr(obj,"IfcAttributes"):
                    a = obj.IfcAttributes
                    for p in properties[pid]:
                        o = ifcfile[p]
                        if o.is_a("IfcPropertySingleValue"):
                            a[o.Name] = str(o.NominalValue)
                    obj.IfcAttributes = a
            
            # color
            if FreeCAD.GuiUp and (pid in colors):
                if DEBUG: print "    setting color: ",colors[pid]
                obj.ViewObject.ShapeColor = colors[pid]
        
            # if DEBUG is on, recompute after each shape
            if DEBUG: FreeCAD.ActiveDocument.recompute()
            
        count += 1
        progressbar.next()
    
    progressbar.stop()
    FreeCAD.ActiveDocument.recompute()
        
    if MERGE_MODE == 3:
        
        if DEBUG: print "Joining shapes..."
        
        for host,children in additions.items():
            if ifcfile[host].is_a("IfcBuildingStorey"):
                compound = []
                for c in children:
                    if c in shapes.keys():
                        compound.append(shapes[c])
                        del shapes[c]
                    if c in additions.keys():
                        for c2 in additions[c]:
                            if c2 in shapes.keys():
                                compound.append(shapes[c2])
                                del shapes[c2]
                if compound:
                    name = ifcfile[host].Name or "Floor"
                    if PREFIX_NUMBERS: name = "ID" + str(host) + " " + name
                    obj = FreeCAD.ActiveDocument.addObject("Part::Feature",name)
                    obj.Label = name
                    obj.Shape = Part.makeCompound(compound)
        if shapes: # remaining shapes
            obj = FreeCAD.ActiveDocument.addObject("Part::Feature","Unclaimed")
            obj.Shape = Part.makeCompound(shapes.values())
            
    else:
        
        if DEBUG: print "Processing relationships..."
        
        # subtractions
        if SEPARATE_OPENINGS:
            for subtraction in subtractions:
                if (subtraction[0] in objects.keys()) and (subtraction[1] in objects.keys()):
                    if DEBUG: print "subtracting ",objects[subtraction[0]].Name, " from ", objects[subtraction[1]].Name
                    Arch.removeComponents(objects[subtraction[0]],objects[subtraction[1]])
                    if DEBUG: FreeCAD.ActiveDocument.recompute()
                    
        # additions
        for host,children in additions.items():
            if host in objects.keys():
                cobs = [objects[child] for child in children if child in objects.keys()]
                if cobs:
                    if DEBUG and (len(cobs) > 10) and ( not(Draft.getType(objects[host]) in ["Site","Building","Floor"])):
                        # avoid huge fusions
                        print "more than 10 shapes to add: skipping."
                    else:
                        if DEBUG: print "adding ",cobs, " to ", objects[host].Name
                        Arch.addComponents(cobs,objects[host])
                        if DEBUG: FreeCAD.ActiveDocument.recompute()
                    
        FreeCAD.ActiveDocument.recompute()
        
        if DEBUG: print "Cleaning..."
            
        # cleaning bad shapes
        for obj in objects.values():
            if obj.isDerivedFrom("Part::Feature"):
                if obj.Shape.isNull():
                    Arch.rebuildArchShape(obj)
                
    FreeCAD.ActiveDocument.recompute()
    
    # 2D elements
    
    if DEBUG and annotations: print "Creating 2D geometry..."
    
    for annotation in annotations:
        aid = annotation.id()
        if aid in skip: continue # user given id skip list
        if "IfcAnnotation" in SKIP: continue # preferences-set type skip list
        name = "Annotation"
        if annotation.Name: name = annotation.Name
        if PREFIX_NUMBERS: name = "ID" + str(aid) + " " + name
        shapes2d = []
        for repres in annotation.Representation.Representations:
            shapes2d.extend(setRepresentation(repres))
        if shapes2d:
            sh = Part.makeCompound(shapes2d)
            pc = str(int((float(count)/(len(products)+len(annotations))*100)))+"% "
            if DEBUG: print pc,"creating object ",aid," : Annotation with shape: ",sh
            o = FreeCAD.ActiveDocument.addObject("Part::Feature",name)
            o.Shape = sh
        count += 1
        
    FreeCAD.ActiveDocument.recompute()
        
    if FreeCAD.GuiUp:
        import FreeCADGui
        FreeCADGui.SendMsgToActiveView("ViewFit")
    print "Finished importing."
    return doc
Ejemplo n.º 9
0
from OCC.TopoDS import TopoDS

import ifcopenshell
import ifcopenshell.geom

# Specify to return pythonOCC shapes from ifcopenshell.geom.create_shape()
settings = ifcopenshell.geom.settings()
settings.set(settings.USE_PYTHON_OPENCASCADE, True)

# Initialize a graphical display window
occ_display = ifcopenshell.geom.utils.initialize_display()
occ_display.View.SetBackgroundImage("white_bg.bmp")

# Open the IFC file using IfcOpenShell
ifc_file = ifcopenshell.open(os.path.join(os.path.dirname(__file__), "IfcOpenHouse.ifc"))

# The geometric elements in an IFC file are the IfcProduct elements. So these are 
# opened and displayed.
products = ifc_file.by_type("IfcProduct")
product_shapes = []

# For every product a shape is created if the shape has a Representation.
for product in products:
    if product.is_a("IfcOpeningElement") or product.is_a("IfcSite"): continue
    if product.Representation is not None:
        shape = ifcopenshell.geom.create_shape(settings, product).geometry
        product_shapes.append((product, shape))

# Two list are initialized to calculate the surface area to be printed.
surface_areas_per_section = []
Ejemplo n.º 10
0
def check_use_of_entities(file_name):
    print ('check use of entities')
    ifc_file = ifcopenshell.open(file_name)
    products = ifc_file.by_type('IfcProduct')
    
    product_list = []
    product_names_list = []

    for product in products:
        product_list.append(product.is_a())
        product_names_list.append([(product.is_a(),product.Name)])
      
        
    ifcproduct_list = (list(OrderedDict.fromkeys(product_list)))
    product_names_list.sort() 
    ifcproduct_name_list = list(product_names_list for product_names_list, _ in itertools.groupby(product_names_list))
                

    root = etree.Element('exchange')
    doc = etree.SubElement(root, "selectionsets")


    for folder_name in ifcproduct_list:
        viewfolder = etree.SubElement(doc, "viewfolder", name=str(folder_name), guid=str(uuid.uuid4()))

        for product in ifcproduct_name_list:
            if product[0][0] == folder_name:
                
                selectionset = etree.SubElement(viewfolder, "selectionset", name=str(product[0][1]), guid=str(uuid.uuid4()))
                
                findspec = etree.SubElement(selectionset, "findspec", mode="all", disjoint="0")
                
                conditions = etree.SubElement(findspec, "conditions")
                
                condition = etree.SubElement(conditions, "condition", test="equals", flags="10")
                
                category = etree.SubElement(condition, "category")
                
                name = etree.SubElement(category, "name", internal="LcIFCProperty").text = "Item"
                    
                property = etree.SubElement(condition, "property")
                name = etree.SubElement(property, "name", internal="IFCString").text = "Name"
                
                value = etree.SubElement(condition, "value")
                data = etree.SubElement(value, "data", type="wstring").text = str(product[0][1])
                
                locator = etree.SubElement(findspec, "locator").text = "/"
                
           
    schema_location_string = '<exchange xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://download.autodesk.com/us/navisworks/schemas/nw-exchange-12.0.xsd">'
    tree = etree.ElementTree(root)
    tree.write('xml_files/ifc_searchsets_navisworks.xml', encoding="utf-8", xml_declaration=True, pretty_print=True)
    
    
    with open('xml_files/ifc_searchsets_navisworks.xml', 'r') as xml_file:
        xml_data = xml_file.readlines()
        
    xml_data[1] = schema_location_string + '\n'
    
    with open('xml_files/ifc_searchsets_navisworks.xml', 'w') as xml_file:
        xml_file.writelines(xml_data)
Ejemplo n.º 11
0
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat May 26 07:14:02 2018

@author: Mathias Bernhard <*****@*****.**>
"""

import ifcopenshell

# file to read
path = '../resources/'
filename = 'MFH Birmensdorf Arch_optimized.ifc'

# open ifc file
ifcfile = ifcopenshell.open(path + filename)

# get a list of all the doors
doors = ifcfile.by_type('IfcDoor')

# output for http://www.webgraphviz.com
graphvizfile = open('../output/door-space-connections_webgraphviz.txt', 'w')
graphvizfile.write('digraph ifc {\n')
graphvizfile.write('graph [rankdir=LR];\n')
graphvizfile.write('node [shape=plaintext,height=0.1,style=filled];\n')
graphvizfile.write('edge [arrowhead=none];\n\n')

uniquespaceids = []
for d in doors:
    di = ifcfile.get_inverse(d)
    rsb = [e for e in di if e.is_a('IfcRelSpaceBoundary')]
Ejemplo n.º 12
0
def display_ifc(file):
    # Specify to return pythonOCC shapes from ifcopenshell.geom.create_shape()
    settings = ifcopenshell.geom.settings()
    settings.set(settings.USE_PYTHON_OPENCASCADE, True)

    # Initialize a graphical display window
    #occ_display = ifcopenshell.geom.utils.initialize_display()

    # Open the IFC file using IfcOpenShell
    ifc_file = ifcopenshell.open(file)
    # The geometric elements in an IFC file are the IfcProduct elements. So these are
    # opened and displayed.

    products = ifc_file.by_type("IfcProduct")
    product_shapes = []

    # For every product a shape is created if the shape has a Representation.
    i = 0
    for product in products:
        if product.is_a("IfcOpeningElement") or product.is_a("IfcSite"):
            continue
        if product.Representation is not None:
            shape = ifcopenshell.geom.create_shape(settings, product).geometry
            product_shapes.append((product, shape))
            i += 1
            print(i)

    # Two list are initialized to calculate the surface area to be printed.
    surface_areas_per_section = []
    surface_areas_per_building = []

    # In this part the sections are created. You can enter the starting height, the
    # maximum height and the height difference between each section.
    starting_height = 0
    maximum_height = 3
    height_step = 0.5

    section_height = starting_height
    while section_height <= maximum_height:
        print("Section height: " + str(section_height))

        # A horizontal plane is created from which a face is constructed to intersect with
        # the building. The face is transparently displayed along with the building.
        section_plane = OCC.gp.gp_Pln(OCC.gp.gp_Pnt(0, 0, section_height),
                                      OCC.gp.gp_Dir(0, 0, 1))
        section_face = BRepBuilderAPI_MakeFace(section_plane, -10, 10, -10,
                                               10).Face()

        #section_face_display = ifcopenshell.geom.utils.display_shape(section_face)
        #ifcopenshell.geom.utils.set_shape_transparency(section_face_display, 0.5)
        #for shape in product_shapes:
        #    ifcopenshell.geom.utils.display_shape(shape[1])
        # Each product of the building is intersected with the horizontal face
        for product, shape in product_shapes:
            section = BRepAlgoAPI_Section(section_face, shape).Shape()
            # The edges of the intersection are stored in a list
            section_edges = list(Topo(section).edges())

            # If the length of the section_edges list is greater than 0 there is an
            # intersection between the plane (at current height) and the product. Only in that
            # case the product needs to be printed.
            if len(section_edges) > 0:
                print("    {:<20}: {}".format(product.is_a(), product.Name))

            # Open Cascade has a function to turn loose unconnected edges into a list of
            # connected wires. This function takes handles (pointers) to Open Cascade's native
            # sequence type. Hence, two sequences and handles, one for the input, one for the
            # output, are created.
            edges = OCC.TopTools.TopTools_HSequenceOfShape()
            edges_handle = OCC.TopTools.Handle_TopTools_HSequenceOfShape(edges)

            wires = OCC.TopTools.TopTools_HSequenceOfShape()
            wires_handle = OCC.TopTools.Handle_TopTools_HSequenceOfShape(wires)

            # The edges are copied to the sequence
            for edge in section_edges:
                edges.Append(edge)

            # A wire is formed by connecting the edges
            OCC.ShapeAnalysis.ShapeAnalysis_FreeBounds.ConnectEdgesToWires(
                edges_handle, 1e-5, True, wires_handle)
            wires = wires_handle.GetObject()

            # From each wire a face is created
            print("        number of faces = %d" % wires.Length())
            for i in range(wires.Length()):
                wire_shape = wires.Value(i + 1)
                wire = OCC.TopoDS.wire(wire_shape)
                face = OCC.BRepBuilderAPI.BRepBuilderAPI_MakeFace(wire).Face()

                # The wires and the faces are displayed
                #ifcopenshell.geom.utils.display_shape(wire)
                #face_display = ifcopenshell.geom.utils.display_shape(face)
                #ifcopenshell.geom.utils.set_shape_transparency(face_display, 0.5)

                # Data about the wire is created to calculate the area
                wire_data = OCC.ShapeExtend.ShapeExtend_WireData(
                    wire, True, True)
                wire_data_handle = OCC.ShapeExtend.Handle_ShapeExtend_WireData(
                    wire_data)

                # The surface area of the face is calculated and appended to the list
                surface_area = abs(
                    OCC.ShapeAnalysis.ShapeAnalysis_TotCross2D(
                        wire_data_handle, face))
                print("        surface area    =", surface_area)
                surface_areas_per_section.append(surface_area)
Ejemplo n.º 13
0
def insert(filename, docname=None, preferences=None):
    """imports the contents of an IFC file in the given document"""

    import ifcopenshell
    from ifcopenshell import geom

    # reset global values
    global layers
    global materials
    global objects
    global adds
    global subs
    layers = {}
    materials = {}
    objects = {}
    adds = {}
    subs = {}

    # statistics
    starttime = time.time()  # in seconds
    filesize = os.path.getsize(filename) * 0.000001  # in megabytes
    print("Opening", filename + ",", round(filesize, 2), "Mb")

    # setup ifcopenshell
    if not preferences:
        preferences = importIFC.getPreferences()
    settings = ifcopenshell.geom.settings()
    settings.set(settings.USE_BREP_DATA, True)
    settings.set(settings.SEW_SHELLS, True)
    settings.set(settings.USE_WORLD_COORDS, True)
    if preferences['SEPARATE_OPENINGS']:
        settings.set(settings.DISABLE_OPENING_SUBTRACTIONS, True)
    if preferences['SPLIT_LAYERS'] and hasattr(settings, "APPLY_LAYERSETS"):
        settings.set(settings.APPLY_LAYERSETS, True)

    # setup document
    if not FreeCAD.ActiveDocument:
        if not docname:
            docname = os.path.splitext(os.path.basename(filename))[0]
        doc = FreeCAD.newDocument(docname)
        doc.Label = docname
        FreeCAD.setActiveDocument(doc.Name)

    # open the file
    ifcfile = ifcopenshell.open(filename)
    progressbar = Base.ProgressIndicator()
    productscount = len(ifcfile.by_type("IfcProduct"))
    progressbar.start("Importing " + str(productscount) + " products...",
                      productscount)
    cores = preferences["MULTICORE"]
    iterator = ifcopenshell.geom.iterator(settings, ifcfile, cores)
    iterator.initialize()
    count = 0

    # process objects
    while True:
        item = iterator.get()
        if item:
            brep = item.geometry.brep_data
            ifcproduct = ifcfile.by_id(item.guid)
            obj = createProduct(ifcproduct, brep)
            progressbar.next(True)
            writeProgress(count, productscount, starttime)
            count += 1
        if not iterator.next():
            break

    # finished
    processRelationships()
    progressbar.stop()
    FreeCAD.ActiveDocument.recompute()
    endtime = round(time.time() - starttime, 1)
    fs = round(filesize, 1)
    ratio = int(endtime / filesize)
    endtime = "%02d:%02d" % (divmod(endtime, 60))
    writeProgress()  # this cleans the line
    print("Finished importing", fs, "Mb in", endtime, "s, or", ratio, "s/Mb")
    return FreeCAD.ActiveDocument
Ejemplo n.º 14
0
def main():
    path = "IfcTestFiles/0014_Vernier112D_ENE_ModèleÉnergétique_R21_1LocalParEtage.ifc"
    ifc_file = ifcopenshell.open(path)
    IfcPatch(path, ifc_file, logger=None, space_ids=[10928,10219]).patch()
Ejemplo n.º 15
0
            "IfcLinearElement"):
        return numpy.row_stack(list(interpret_linear_element(settings, elem)))
    else:
        return ifcopenshell.geom.create_shape(settings, elem)


def print_structure(alignment, indent=0):
    """
    Debugging function to print alignment decomposition
    """
    print(" " * indent, str(alignment)[0:100])
    for rel in alignment.IsNestedBy:
        for child in rel.RelatedObjects:
            print_structure(child, indent + 2)


if __name__ == "__main__":
    import sys
    from matplotlib import pyplot as plt

    s = ifcopenshell.express.parse("IFC4x3_RC3.exp")
    ifcopenshell.register_schema(s)
    f = ifcopenshell.open(sys.argv[1])
    print_structure(f.by_type("IfcAlignment")[0])

    al_hor = f.by_type("IfcAlignmentHorizontal")[0]
    xy = create_shape({}, al_hor)

    plt.plot(xy.T[0], xy.T[1])
    plt.savefig("horizontal_alignment.png")
Ejemplo n.º 16
0
import operator

import OCC.GProp
import OCC.BRepGProp

import ifcopenshell
import ifcopenshell.geom

import numpy

# RGBA colors for the visualisation of elements
RED, GRAY = (1,0,0,1), (0.6, 0.6, 0.6, 0.1)

# Model freely available at:
# http://www.nibs.org/?page=bsa_commonbimfiles
ifc_file = ifcopenshell.open("Duplex_A_20110907_optimized.ifc")

# Settings to specify usage of pyOCC
settings = ifcopenshell.geom.settings()
settings.set(settings.USE_PYTHON_OPENCASCADE, True)

# Some helper functions to map to the list of walls
def create_shape(elem):
    return ifcopenshell.geom.create_shape(settings, elem)

def calc_volume(s):
    props = OCC.GProp.GProp_GProps()
    OCC.BRepGProp.brepgprop_VolumeProperties(s.geometry, props)
    return props.Mass()
    
def calc_area(s):
import sys
sys.path.append('../..')

import WebServer.TornadoWeb
import tornado.ioloop

import ifcopenshell
import ifcopenshell.geom

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

f = ifcopenshell.open("IfcOpenHouse.ifc")


def generate_shapes():
    for product in f.by_type("IfcProduct"):
        if product.is_a("IfcOpeningElement"):
            continue
        if product.Representation:
            try:
                shape = ifcopenshell.geom.create_shape(settings, product).geometry
                yield product.is_a(), shape
            except:
                pass

colors = {'IfcRoof': (0.6, 0.2, 0.1),
          'IfcPlate': (0.4, 0.7, 0.8),
          'IfcMember': (0.5, 0.3, 0.1),
          'IfcSite': (0.2, 0.4, 0.1)}
Ejemplo n.º 18
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec  4 12:55:59 2019

@author: 谢秉辰
"""

import ifcopenshell
import ezdxf
ifc_file = ifcopenshell.open("example.ifc")


#展示IFC文件中有哪些类型的节点
def print_type(ifc_file):
    products = ifc_file.by_type('IfcProduct')
    dock = []
    for product in products:
        flag = 0
        ship = product.is_a()
        for ship_ in dock:
            if ship == ship_:
                flag += 1
                break
        if flag == 0:
            dock.append(ship)
            print(ship)
        #product.ObjectPlacement.RelativePlacement.Location[0]


#获取IFC文件中的所有Port
Ejemplo n.º 19
0
#18=IFCCONVERSIONBASEDUNIT(#12,.PLANEANGLEUNIT.,'DEGREE',#17);
#19=IFCUNITASSIGNMENT((#13,#14,#15,#18));
#20=IFCPROJECT('%(project_globalid)s',#5,'%(project_name)s',$,$,$,$,(#11),#19);
ENDSEC;
END-ISO-10303-21;
""" % locals()


# Write the template to a temporary file
temp_handle, temp_filename = tempfile.mkstemp(suffix=".ifc")
#pdb.set_trace()
with open(temp_filename, "wb") as f:
    f.write(template)

# Obtain references to instances defined in template
ifcfile = ifcopenshell.open(temp_filename)
owner_history = ifcfile.by_type("IfcOwnerHistory")[0]
project = ifcfile.by_type("IfcProject")[0]
context = ifcfile.by_type("IfcGeometricRepresentationContext")[0]

# IFC hierarchy creation
site_placement = create_ifclocalplacement(ifcfile)
site = ifcfile.createIfcSite(create_guid(), owner_history, "Site", None, None, site_placement, None, None, "ELEMENT", None, None, None, None, None)
print("site %s" % site)


building_placement = create_ifclocalplacement(ifcfile, relative_to=site_placement)
building = ifcfile.createIfcBuilding(create_guid(), owner_history, 'Building', None, None, building_placement, None, None, "ELEMENT", None, None, None)

storey_placement = create_ifclocalplacement(ifcfile, relative_to=building_placement)
elevation = 0.0
Ejemplo n.º 20
0
 def load(self):
     print("Loading old file ...")
     self.old = ifcopenshell.open(self.old_file)
     print("Loading new file ...")
     self.new = ifcopenshell.open(self.new_file)
Ejemplo n.º 21
0
def insert(filename,docname,skip=[]):
    "imports the contents of an IFC file"
    
    try:
        import ifcopenshell
    except:
        if DEBUG: print "using legacy importer"
        import importIFClegacy
        return importIFClegacy.insert(filename,docname,skip)

    p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch")
    DEBUG = p.GetBool("ifcDebug",False)
    PREFIX_NUMBERS = p.GetBool("ifcPrefixNumbers",False)
    SKIP = p.GetString("ifcSkip","")
    SEPARATE_OPENINGS = p.GetBool("ifcSeparateOpenings",False)
    SCALE = p.GetFloat("IfcScalingFactor",1.0)

    if DEBUG: print "opening ",filename,"..."
    try:
        doc = FreeCAD.getDocument(docname)
    except:
        doc = FreeCAD.newDocument(docname)
    FreeCAD.ActiveDocument = doc
    
    global ifcfile # keeping global for debugging purposes
    ifcopenshell.clean()
    ifcfile = ifcopenshell.open(filename)
    shape_attributes = ifcopenshell.SEW_SHELLS
    if SEPARATE_OPENINGS: shape_attributes += ifcopenshell.DISABLE_OPENING_SUBTRACTIONS
    sites = ifcfile.by_type("IfcSite")
    buildings = ifcfile.by_type("IfcBuilding")
    floors = ifcfile.by_type("IfcBuildingStorey")
    products = ifcfile.by_type("IfcProduct")
    openings = ifcfile.by_type("IfcOpeningElement")

    # building relations tables
    objects = {} # { id:object, ... }
    additions = {} # { host:[child,...], ... }
    subtractions = [] # [ [opening,host], ... ]
    for r in ifcfile.by_type("IfcRelContainedInSpatialStructure"):
        additions.setdefault(r.RelatingStructure.id(),[]).extend([e.id() for e in r.RelatedElements])
    for r in ifcfile.by_type("IfcRelAggregates"):
        additions.setdefault(r.RelatingObject.id(),[]).extend([e.id() for e in r.RelatedObjects])
    for r in ifcfile.by_type("IfcRelVoidsElement"):
        subtractions.append([r.RelatedOpeningElement.id(), r.RelatingBuildingElement.id()])

    # products
    for product in products:
        pid = product.id()
        guid = product.GlobalId
        ptype = product.is_a()
        name = product.Name or str(ptype[3:])
        if PREFIX_NUMBERS: name = "ID" + str(pid) + " " + name
        obj = None
        baseobj = None
        
        if (ptype == "IfcOpeningElement") and (not SEPARATE_OPENINGS): continue
        if pid in skip: continue
        if ptype in SKIP: continue
        
        brep = ifcopenshell.create_shape(product,shape_attributes)
        if brep:
            shape = Part.Shape()
            shape.importBrepFromString(brep)
            if SCALE != 1:
                shape.scale(SCALE)
            if not shape.isNull():
                baseobj = FreeCAD.ActiveDocument.addObject("Part::Feature",name+"_body")
                baseobj.Shape = shape
        for freecadtype,ifctypes in typesmap.iteritems():
            if ptype in ifctypes:
                obj = getattr(Arch,"make"+freecadtype)(baseobj=baseobj,name=name)
                obj.Label = name
                # setting uid
                if hasattr(obj,"IfcAttributes"):
                    a = obj.IfcAttributes
                    a["IfcUID"] = str(guid)
                    obj.IfcAttributes = a
                break
        if not obj:
            obj = baseobj
        if obj:
            sh = baseobj.Shape.ShapeType if hasattr(baseobj,"Shape") else "None"
            sols = str(baseobj.Shape.Solids) if hasattr(baseobj,"Shape") else ""
            if DEBUG: print "creating object ",pid," : ",ptype, " with shape: ",sh," ",sols
            objects[pid] = obj

    # subtractions
    if SEPARATE_OPENINGS:
        for subtraction in subtractions:
            if (subtraction[0] in objects.keys()) and (subtraction[1] in objects.keys()):
                    Arch.removeComponents(objects[subtraction[0]],objects[subtraction[1]])

    # additions
    for host,children in additions.iteritems():
        if host in objects.keys():
            cobs = [objects[child] for child in children if child in objects.keys()]
            if cobs:
                Arch.addComponents(cobs,objects[host])

    FreeCAD.ActiveDocument.recompute()
    
    # cleaning bad shapes
    for obj in objects.values():
        if obj.isDerivedFrom("Part::Feature"):
            if obj.Shape.isNull():
                Arch.rebuildArchShape(obj)
    FreeCAD.ActiveDocument.recompute()
    
    if FreeCAD.GuiUp:
        import FreeCADGui
        FreeCADGui.SendMsgToActiveView("ViewFit")
    return doc
Ejemplo n.º 22
0
print(time.strftime("%Y/%m/%d %H:%M", time.strptime(time.ctime())))

typeDict = IfcTypeDict()

assert typeDict["IfcWall"] == ('GlobalId', 'OwnerHistory', 'Name',
                               'Description', 'ObjectType', 'ObjectPlacement',
                               'Representation', 'Tag')

nodes = []
edges = []

# wallid = None

ourLabel = 'test'

f = ifcopenshell.open(ifc_path)

for el in f:
    if el.is_a() == "IfcOwnerHistory":
        continue
    tid = el.id()
    cls = el.is_a()
    pairs = []
    keys = []
    try:
        keys = [
            x for x in el.get_info()
            if x not in ["type", "id", "OwnerHistory"]
        ]
    except RuntimeError:
        # we actually can't catch this, but try anyway
Ejemplo n.º 23
0
import ifcopenshell
import pyqrcode
from pyqrcode import QRCode
import openpyxl
from openpyxl import Workbook
import os

ifcfile = ifcopenshell.open('U:\\47_QR_codes\\flat_11_ruimtemodel.ifc')
products = ifcfile.by_type('IfcProduct')
ifczones = ifcfile.by_type('IfcZone')


def get_checklist_details():
    print("get meterkastlijst data uit bimfield")

    wb = openpyxl.load_workbook(
        "bimfield_files/meterkastlijst_van_bimfield.xlsx")
    ws = wb.get_sheet_by_name("Blad1")

    row_count = ws.max_row
    column_count = ws.max_column

    j = 13

    project_data_list = []

    for i in range(1, row_count):

        if (ws.cell(row=i + 1, column=j).value) is not None:
            project_data_list.append([(ws.cell(row=i + 1, column=9).value),
                                      (ws.cell(row=i + 1, column=j).value),
Ejemplo n.º 24
0
import ifcopenshell
import sys

#inputFileName= sys.argv[1]
inputFileName = './beams.ifc'

ifc_file = ifcopenshell.open(inputFileName)
products = ifc_file.by_type('IfcProduct')
beams = list()
for product in products:
    print(product.is_a())
    if (product.is_a('IfcBeamStandardCase')):
        beams.append(product)

for b in beams:
    print('beam Description:', b.Description)
Ejemplo n.º 25
0
    def start(self):

        # Read  in the BDNS naming abbreviation
        bdns_csv = pd.read_csv(URL_BDNS)
        bdns_abb = bdns_csv[['abbreviation', 'ifc_class']]

        # Read  in the ifc file
        f = ifcopenshell.open(self.ifc_input)
        products = f.by_type('IfcProduct')

        # Create a df with all ifc classes
        d = []
        for product in products:
            asset_name = ''
            definitions = product.IsDefinedBy
            for definition in definitions:
                if 'IfcRelDefinesByProperties' == definition.is_a():
                    property_definition = definition.RelatingPropertyDefinition
                    if 'Data' == property_definition.Name:
                        for par in property_definition.HasProperties:
                            if par.Name == 'asset_name':
                                asset_name = par.NominalValue[0]
            d.append({
                'ifc_class': product.is_a(),
                'asset_guid': product.GlobalId,
                'RevitName': product.Name,
                'asset_name': asset_name,
            })

        df = pd.DataFrame(d)
        res = pd.merge(df, bdns_abb, how='left',
                       on=['ifc_class'
                           ]).dropna(subset=['asset_name', 'abbreviation'])
        res['RevitTag'] = res['RevitName'].astype(str).apply(
            lambda x: x.split(':')[-1])

        if self.BDNS_validation:

            BDNSVal = BDNSValidator(res)

            print('The following devices fail the GUID validation tests:')
            failed_GUID = BDNSVal.validate_GUID()
            print("-------------------")

            print(
                'The following devices fail the device role name validation tests:'
            )
            failed_DeviceName = BDNSVal.validate_DeviceName()
            print("-------------------")

            print(
                'The following devices fail to follow the BDNS abbreviation:')
            faild_abb = BDNSVal.validate_abb(bdns_csv)
            print("-------------------")

            str_list = failed_GUID + failed_DeviceName + faild_abb
            res['color_text'] = np.where(res['asset_name'].isin(str_list),
                                         'red', 'black')

            checkdup = BDNSVal.check_duplicates()
            if not checkdup.empty:
                print("Duplicate GUID are:")
                print(checkdup)
                print("-------------------")

        # Generate QR code
        if res.empty:
            print('None of the ifc classes matches the BDNS ones .....')
        else:
            res.apply(self.create_qrcode, boxsize=10, axis=1)
def processItem(item):
    settings = ifcopenshell.geom.settings()
    settings.set(settings.USE_BREP_DATA, True)
    settings.set(settings.SEW_SHELLS, True)
    settings.set(settings.USE_WORLD_COORDS, True)
    settings.set(settings.DISABLE_OPENING_SUBTRACTIONS, True)

    ifc_file = ifcopenshell.open("C:/BIM2BEM/ExternalEarth_R20_IFC4.ifc")

    body_context = next(
        (item
         for item in ifc_file.by_type("IfcGeometricRepresentationSubContext")
         if item.ContextIdentifier == "Body"), None)
    top_building = None
    if body_context is None:
        parent_context = next(
            (item
             for item in ifc_file.by_type("IfcGeometricRepresentationContext")
             if item.ContextType == "Model"), None)
        body_context = ifc_file.createIfcGeometricRepresentationSubContext(
            "Body", "Model", None, None, None, None, parent_context, None,
            "MODEL_VIEW", None)

    ifc_building_element_cells = []
    for ifc_building_element in ifc_file.by_type('IfcBuildingElement'):
        if not (ifc_building_element.is_a('IfcWall')
                or ifc_building_element.is_a('IfcSlab')):
            continue

        ifc_building_element_cell = getCell(settings, ifc_building_element)
        setDictionary(ifc_building_element_cell, "IfcBuildingElement",
                      ifc_building_element.GlobalId)
        ifc_building_element_cells.append(ifc_building_element_cell)

        int_bounds = []
        ifc_building_element_cell.InternalBoundaries(int_bounds)
        for shell in int_bounds:
            md = meshData(shell)
            for f in md[1]:
                createRelConnectsElements(ifc_file, ifc_building_element,
                                          ifc_building_element, md[0], f)
    top_building = CellComplex.ByCells(ifc_building_element_cells)
    transferDictionaries(ifc_building_element_cells,
                         getSubTopologies(top_building, Cell), 1e-3)

    for face in getSubTopologies(top_building, Face):
        ajacent_cells = []
        _ = FaceUtility.AdjacentCells(face, top_building, ajacent_cells)
        ajacent_cells = list(ajacent_cells)
        if len(ajacent_cells) > 1:
            relating_elem = ifc_file.by_guid(
                getDictionary(ajacent_cells[0], "IfcBuildingElement"))
            related_elem = ifc_file.by_guid(
                getDictionary(ajacent_cells[1], "IfcBuildingElement"))
            md = meshData(face)
            createRelConnectsElements(ifc_file, relating_elem, related_elem,
                                      md[0], md[1][0])
        else:
            ifc_building_element = ifc_file.by_guid(
                getDictionary(ajacent_cells[0], "IfcBuildingElement"))
            setDictionary(face, "IfcBuildingElement",
                          ifc_building_element.GlobalId)

    cells = []
    ext_boundary = getSubTopologies(top_building,
                                    CellComplex)[0].ExternalBoundary()
    transferDictionaries(getSubTopologies(top_building, Face),
                         getSubTopologies(ext_boundary, Face), 1e-3)
    for shell in getSubTopologies(ext_boundary, Shell):
        cell = Cell.ByShell(shell)
        if CellUtility.Volume(cell) < 1e-6:
            continue

        cell_storey, elevation = None, None
        for face in getSubTopologies(shell, Face):
            ifc_building_element = ifc_file.by_guid(
                getDictionary(face, "IfcBuildingElement"))
            if not ifc_building_element.ContainedInStructure:
                ifc_building_element = ifc_building_element.Decomposes[
                    0].RelatingObject
            ifc_building_storey = ifc_building_element.ContainedInStructure[
                0].RelatingStructure
            if elevation is None or ifc_building_storey.Elevation < elevation:
                cell_storey, elevation = ifc_building_storey, ifc_building_storey.Elevation
        transferDictionaries(getSubTopologies(shell, Face),
                             getSubTopologies(cell, Face), 1e-3)
        setDictionary(cell, "IfcBuildingStorey", cell_storey.GlobalId)
        cells.append(cell)

    cells.sort(key=lambda cell: CellUtility.Volume(cell))
    for idx_space, cell in enumerate(cells[:-1]):
        ifc_space = ifcopenshell.api.run("root.create_entity",
                                         ifc_file,
                                         ifc_class="IfcSpace")
        ifc_space.CompositionType = "ELEMENT"
        ifc_space.PredefinedType = "INTERNAL"
        ifc_building_storey = ifc_file.by_guid(
            getDictionary(cell, "IfcBuildingStorey"))
        ifc_space.Name = "Space " + str(len(ifc_file.by_type('IfcSpace')) - 1)
        ifcopenshell.api.run("aggregate.assign_object",
                             ifc_file,
                             product=ifc_space,
                             relating_object=ifc_building_storey)
        md = meshData(cell)
        o, z = None, None
        for v in md[0]:
            if z is None or v[-1] < z:
                o, z = v, v[-1]
        space_matrix = np.linalg.solve(
            ifcopenshell.util.placement.get_local_placement(
                ifc_building_storey.ObjectPlacement),
            ifcopenshell.util.placement.a2p(o, np.array([0, 0, 1]),
                                            np.array([1, 0, 0])))
        point_list = ifc_file.createIfcCartesianPointList3D([
            np.linalg.solve(space_matrix, np.append(v, 1))[:-1].tolist()
            for v in md[0]
        ])
        indexed_faces = [
            ifc_file.createIfcIndexedPolygonalFace([index + 1 for index in f])
            for f in md[1]
        ]
        representation = ifc_file.createIfcPolygonalFaceSet(
            point_list, None, indexed_faces, None)
        shape = ifc_file.createIfcShapeRepresentation(
            body_context, body_context.ContextIdentifier, "Tessellation",
            [representation])
        ifcopenshell.api.run("geometry.assign_representation",
                             ifc_file,
                             product=ifc_space,
                             representation=shape)
        ifcopenshell.api.run("geometry.edit_object_placement",
                             ifc_file,
                             product=ifc_space,
                             matrix=space_matrix)
        for face in getSubTopologies(cell, Face):
            setDictionary(face, "IfcSpace", ifc_space.GlobalId)
        transferDictionaries(getSubTopologies(cell, Face),
                             getSubTopologies(top_building, Face), 1e-3)

    for cell in getSubTopologies(top_building, Cell):
        ifc_building_element = ifc_file.by_guid(
            getDictionary(cell, "IfcBuildingElement"))
        faces = [
            face for face in getSubTopologies(cell, Face) if ifc_file.by_guid(
                getDictionary(face, "IfcBuildingElement")) is not None
        ]

        top_opening_elements = []
        for ifc_rel_voids_element in ifc_building_element.HasOpenings:
            ifc_opening_element = ifc_rel_voids_element.RelatedOpeningElement
            top_opening_element = getCell(settings, ifc_opening_element)
            if not ifc_opening_element.HasFillings:
                continue

            setDictionary(
                top_opening_element, "IfcElement", ifc_opening_element.
                HasFillings[0].RelatedBuildingElement.GlobalId)
            top_opening_elements.append(top_opening_element)

        space_boundary_2bs = [face for face in faces]
        for idx, face in enumerate(faces):
            normal = FaceUtility.NormalAtParameters(face, 0.5, 0.5)
            n = np.array([normal[0], normal[1], normal[2]])
            point = FaceUtility.VertexAtParameters(face, 0.5, 0.5)
            p = np.array([point.X(), point.Y(), point.Z()])
            d = np.dot(n, p)

            ifc_space = ifc_file.by_guid(getDictionary(face, "IfcSpace"))
            for other_idx, other_face in enumerate(faces[idx + 1:]):
                other_normal = FaceUtility.NormalAtParameters(
                    other_face, 0.5, 0.5)
                other_n = np.array(
                    [other_normal[0], other_normal[1], other_normal[2]])
                if np.dot(n, other_n) + 1 > 1e-6:
                    continue

                other_point = FaceUtility.VertexAtParameters(
                    other_face, 0.5, 0.5)
                other_p = np.array(
                    [other_point.X(),
                     other_point.Y(),
                     other_point.Z()])
                dist = -np.dot(n, other_p) + d
                if dist < 1e-6:
                    continue

                top_space_boundary = boolean(
                    face,
                    TopologyUtility.Translate(other_face, dist * normal[0],
                                              dist * normal[1],
                                              dist * normal[2]), "Intersect")
                if top_space_boundary is None:
                    continue

                top_space_boundary = getSubTopologies(top_space_boundary, Face)
                if not top_space_boundary:
                    continue

                top_space_boundary = top_space_boundary[0]
                other_ifc_space = ifc_file.by_guid(
                    getDictionary(faces[idx + other_idx + 1], "IfcSpace"))
                ifc_rel_space_boundary, space_boundary_2bs[
                    idx] = createRelSpaceBoundary1and2a(
                        ifc_file, top_space_boundary, True, ifc_space,
                        other_ifc_space, ifc_building_element,
                        space_boundary_2bs[idx])
                other_top_space_boundary = getSubTopologies(
                    TopologyUtility.Translate(top_space_boundary,
                                              -dist * normal[0],
                                              -dist * normal[1],
                                              -dist * normal[2]), Face)[0]
                other_ifc_rel_space_boundary, space_boundary_2bs[
                    idx + other_idx + 1] = createRelSpaceBoundary1and2a(
                        ifc_file, other_top_space_boundary, False,
                        other_ifc_space, ifc_space, ifc_building_element,
                        space_boundary_2bs[idx + other_idx + 1])

                if ifc_rel_space_boundary is not None and other_ifc_rel_space_boundary is not None:
                    ifc_rel_space_boundary.CorrespondingBoundary = other_ifc_rel_space_boundary
                    other_ifc_rel_space_boundary.CorrespondingBoundary = ifc_rel_space_boundary

                for top_opening_element in top_opening_elements:
                    ifc_inner_boundary = createInnerBoundary(
                        ifc_rel_space_boundary, top_opening_element,
                        top_space_boundary, True)
                    other_ifc_inner_boundary = createInnerBoundary(
                        other_ifc_rel_space_boundary, top_opening_element,
                        other_top_space_boundary, False)

                    if ifc_inner_boundary is not None and other_ifc_inner_boundary is not None:
                        ifc_inner_boundary.CorrespondingBoundary = other_ifc_inner_boundary
                        other_ifc_inner_boundary.CorrespondingBoundary = ifc_inner_boundary

        for face, space_boundary_2b in zip(faces, space_boundary_2bs):
            ifc_space = ifc_file.by_guid(getDictionary(face, "IfcSpace"))
            if ifc_space is not None:
                vertices, fs = meshData(space_boundary_2b)
                for f in fs:
                    createRelSpaceBoundary(ifc_file,
                                           "IfcRelSpaceBoundary2ndLevel",
                                           ifc_space, ifc_building_element,
                                           vertices, f[::-1], "INTERNAL")

    ifc_file.write("C:/BIM2BEM/output.ifc")

    # model = openstudio.model.Model()
    # ifc2os = {}

    # for ifc_material_layer in ifc_file.by_type('IfcMaterialLayer'):
    # if not ifc_material_layer.ToMaterialLayerSet:
    # continue

    # os_standard_opaque_material = openstudio.model.StandardOpaqueMaterial(model)
    # os_standard_opaque_material.setName(ifc_material_layer.Name)
    # os_standard_opaque_material.setThickness(float(ifc_material_layer.LayerThickness))
    # ifc2os[ifc_material_layer] = os_standard_opaque_material

    # for ifc_material_layer_set in ifc_file.by_type('IfcMaterialLayerSet'):
    # if not ifc_material_layer_set.AssociatedTo:
    # continue

    # os_construction = openstudio.model.Construction(model)
    # os_construction.setName(ifc_material_layer_set.LayerSetName)
    # os_construction.setLayers([ifc2os[ifc_material_layer] for ifc_material_layer in ifc_material_layer_set.MaterialLayers])
    # ifc2os[ifc_material_layer_set] = os_construction

    # for ifc_building_storey in ifc_file.by_type('IfcBuildingStorey'):
    # if not ifc_building_storey.IsDecomposedBy:
    # continue

    # ifc_spaces = [x for x in ifc_building_storey.IsDecomposedBy[0].RelatedObjects if x.is_a("IfcSpace")]
    # if not ifc_spaces:
    # continue

    # os_building_story = openstudio.model.BuildingStory(model)
    # os_building_story.setName(ifc_building_storey.Name)
    # os_building_story.setNominalZCoordinate(float(ifc_building_storey.Elevation))
    # for ifc_space in ifc_spaces:
    # os_space = openstudio.model.Space(model)
    # os_space.setName(ifc_space.Name)
    # os_space.setBuildingStory(os_building_story)
    # space_matrix = ifcopenshell.util.placement.get_local_placement(ifc_space.ObjectPlacement)
    # for ifc_space_boundary in ifc_space.BoundedBy:
    # if ifc_space_boundary.ParentBoundary is not None:
    # continue

    # os_surface = openstudio.model.Surface(getVertices(ifc_space_boundary, space_matrix), model)
    # os_surface.setName(ifc_space_boundary.Name)
    # os_surface.setSpace(os_space)
    # if ifc_space_boundary.InternalOrExternalBoundary == "INTERNAL":
    # if ifc_space_boundary.CorrespondingBoundary is None:
    # os_surface.setOutsideBoundaryCondition("Adiabatic")
    # elif ifc_space_boundary.CorrespondingBoundary in ifc2os:
    # os_surface.setAdjacentSurface(ifc2os[ifc_space_boundary.CorrespondingBoundary])
    # else:
    # os_surface.setOutsideBoundaryCondition("Outdoors")
    # ifc_building_element = ifc_space_boundary.RelatedBuildingElement
    # ifc_rel_associates = ifc_building_element.HasAssociations
    # if ifc_building_element.IsTypedBy:
    # ifc_rel_associates = ifc_building_element.IsTypedBy[0].RelatingType.HasAssociations
    # ifc_rel_associates_material = next((x for x in ifc_rel_associates if x.is_a("IfcRelAssociatesMaterial")), None)
    # if ifc_rel_associates_material is not None:
    # os_surface.setConstruction(ifc2os[ifc_rel_associates_material.RelatingMaterial])
    # ifc2os[ifc_space_boundary] = os_surface

    # for ifc_inner_boundary in ifc_space_boundary.InnerBoundaries:
    # if ifc_inner_boundary.ParentBoundary != ifc_space_boundary:
    # continue

    # os_sub_surface = openstudio.model.SubSurface(getVertices(ifc_inner_boundary, space_matrix), model)
    # os_sub_surface.setName(ifc_inner_boundary.Name)
    # os_sub_surface.setSurface(os_surface)
    # if (ifc_inner_boundary.InternalOrExternalBoundary == "INTERNAL" and
    # ifc_inner_boundary.CorrespondingBoundary is not None and
    # ifc_inner_boundary.CorrespondingBoundary in ifc2os):
    # os_sub_surface.setAdjacentSubSurface(ifc2os[ifc_inner_boundary.CorrespondingBoundary])
    # ifc2os[ifc_inner_boundary] = os_sub_surface

    # model.save(openstudio.toPath("C:/BIM2BEM/output.osm"), True)

    print("FIN")
Ejemplo n.º 27
0
import xml.etree.ElementTree as et
import ifcopenshell
import openpyxl
import time
import datetime
from collections import defaultdict
import sqlite3 as lite
import sys
from os.path import isfile
import externalfunctions
import os

requirements = openpyxl.load_workbook('quality_requirements.xlsx')
schedule = et.parse('UITVOERINGSTIJDSCHEMA.xml')
file = ifcopenshell.open('Situatie_totaal4D.ifc')
root = schedule.getroot()
link_between_obj_task = file.by_type("ifcrelassignstoprocess")
progress = []
completed = []
related_object = []
items = defaultdict(list)  # what does this do??!!
# Get the complete list of activities from the project schedule: name of each activity, percentageComplete and it's start date (Tuples)
for named_tasks in root.iter('{http://schemas.microsoft.com/project}Task'):
    value = named_tasks.findtext(
        '{http://schemas.microsoft.com/project}PercentComplete')
    name = named_tasks.findtext('{http://schemas.microsoft.com/project}Name')
    summary = named_tasks.findtext(
        '{http://schemas.microsoft.com/project}Summary')
    start_string = ""
    startxml = named_tasks.findtext(
        '{http://schemas.microsoft.com/project}Start')
Ejemplo n.º 28
0
fixed_length = {
    ('IfcCartesianPoint', 'Coordinates'): 3,
    ('IfcDirection', 'DirectionRatios'): 3,
    ('IfcProductDefinitionShape', 'Representations'): 1,
    ('IfcShapeRepresentation', 'Items'): 1,
    ('IfcRelAssignsToProduct', 'RelatedObjects'): 1
}
xref = [('IfcGridOffsetList', 'Offsets'), ('IfcGrid', 'UAxes'),
        ('IfcGrid', 'VAxes')]
precision = 32 if SINGLE_PRECISION else 64
mapping = hdf5_mapping.hdf5_mapping(ifc.schema,
                                    f,
                                    ignore=ignored,
                                    fix_length=fixed_length,
                                    force_xref=xref,
                                    precision=precision)

print "Reading SPF data"

ifcf = ifcopenshell.open(IFC_FN)

print "Creating HDF5 instance population"

mapping.create_population("Haus30_population",
                          ifcf,
                          compressed=USE_COMPRESSION)

f.close()

print "Done :)"
Ejemplo n.º 29
0
                assert_valid_inverse(attr, val)
            except ValidationError as e:
                if hasattr(logger, "set_instance"):
                    logger.error(str(e))
                else:
                    logger.error("In %s\n%s", inst, e)


if __name__ == "__main__":
    import sys
    import logging

    filenames = [x for x in sys.argv[1:] if not x.startswith("--")]
    flags = set(x for x in sys.argv[1:] if x.startswith("--"))

    for fn in filenames:
        if "--json" in flags:
            logger = json_logger()
        else:
            logger = logging.getLogger("validate")
            logger.setLevel(logging.DEBUG)

        f = ifcopenshell.open(fn)

        print("Validating", fn, file=sys.stderr)
        validate(f, logger)

        if "--json" in flags:
            print("\n".join(
                json.dumps(x, default=str) for x in logger.statements))
Ejemplo n.º 30
0
aNugget = os.path.join(
    FindDIR, InternalPATH,
    "BIM_Projekt_Golden_Nugget-Architecture_Structural_optimized.ifc")
mepNugget = os.path.join(
    FindDIR, InternalPATH,
    "BIM_Projekt_Golden_Nugget-Building_Services_optimized.ifc")
aDuplex = os.path.join(FindDIR, InternalPATH,
                       "Duplex_A_20110907_optimized.ifc")
mepDuplex = os.path.join(FindDIR, InternalPATH,
                         "Duplex_M_20111024_optimized.ifc")
"""
##########################################################################################
In the model variable you can change the variable to get location data of different models.
##########################################################################################
"""
model = ifcopenshell.open(aDuplex)
print("\nIt took {} second to load Model\n".format(time.perf_counter() -
                                                   timeStart))

#Find XLSX Output Path
OutputPATH = os.path.join(FindDIR, "output\\future_format.xlsx")
workbook = xlsxwriter.Workbook(OutputPATH)

worksheet = workbook.add_worksheet("Summary")
text = "This workbook contain location information. For now the information is represented as coordinates relative to other objects in the ifc three up through IfcBuilding, IfcSite and IfcProject. For shape geometric data another software might be needed to be able to read the data, and analyze it. As for IfcOpenShell comments on Github advise against shape manipulation, as it would be too complex."

worksheet.write(0, 0, text)

#Create a list with possible Entities
productList = []
for product in model.by_type("IfcProduct"):
Ejemplo n.º 31
0
def export(exportList,filename):
    "exports FreeCAD contents to an IFC file"
    
    p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch")
    FORCEBREP = p.GetBool("ifcExportAsBrep",False)
    DEBUG = p.GetBool("ifcDebug",False) 

    try:
        global ifcopenshell
        import ifcopenshell
    except:
        FreeCAD.Console.PrintError("IfcOpenShell was not found on this system. IFC support is disabled\n")
        return
        
    if isinstance(filename,unicode): 
        import sys #workaround since ifcopenshell currently can't handle unicode filenames
        filename = filename.encode(sys.getfilesystemencoding())

    version = FreeCAD.Version()
    owner = FreeCAD.ActiveDocument.CreatedBy
    email = ''
    if ("@" in owner) and ("<" in owner):
        s = owner.split("<")
        owner = s[0]
        email = s[1].strip(">")
    global ifctemplate
    ifctemplate = ifctemplate.replace("$version",version[0]+"."+version[1]+" build "+version[2])
    ifctemplate = ifctemplate.replace("$owner",owner)
    ifctemplate = ifctemplate.replace("$company",FreeCAD.ActiveDocument.Company)
    ifctemplate = ifctemplate.replace("$email",email)
    ifctemplate = ifctemplate.replace("$now",str(int(time.time())))
    ifctemplate = ifctemplate.replace("$projectid",FreeCAD.ActiveDocument.Uid[:22].replace("-","_"))
    ifctemplate = ifctemplate.replace("$project",FreeCAD.ActiveDocument.Name)
    ifctemplate = ifctemplate.replace("$filename",filename)
    ifctemplate = ifctemplate.replace("$timestamp",str(time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime())))
    template = tempfile.mkstemp(suffix=".ifc")[1]
    of = pyopen(template,"wb")
    of.write(ifctemplate)
    of.close()
    global ifcfile, surfstyles
    ifcfile = ifcopenshell.open(template)
    history = ifcfile.by_type("IfcOwnerHistory")[0]
    context = ifcfile.by_type("IfcGeometricRepresentationContext")[0]
    project = ifcfile.by_type("IfcProject")[0]
    objectslist = Draft.getGroupContents(exportList,walls=True,addgroups=True)
    objectslist = Arch.pruneIncluded(objectslist)
    products = {} # { Name: IfcEntity, ... }
    surfstyles = {} # { (r,g,b): IfcEntity, ... }
    count = 1
    
    # products
    for obj in objectslist:
        
        # getting generic data
        name = str(obj.Label)
        description = str(obj.Description) if hasattr(obj,"Description") else ""
            
        # getting uid
        uid = None
        if hasattr(obj,"IfcAttributes"):
            if "IfcUID" in obj.IfcAttributes.keys():
                uid = str(obj.IfcAttributes["IfcUID"])
        if not uid:
            uid = ifcopenshell.guid.compress(uuid.uuid1().hex)
            
        # setting the IFC type + name conversions
        if hasattr(obj,"Role"):
            ifctype = obj.Role.replace(" ","")
        else:
            ifctype = Draft.getType(obj)
        if ifctype in translationtable.keys():
            ifctype = translationtable[ifctype]
        ifctype = "Ifc" + ifctype
        if ifctype == "IfcGroup":
            continue
        ifctypes = []
        for v in typesmap.values():
            ifctypes.extend(v)
        if not ifctype in ifctypes:
            ifctype = "IfcBuildingElementProxy"
        
        # getting the "Force BREP" flag
        brepflag = False
        if hasattr(obj,"IfcAttributes"):
            if "FlagForceBrep" in obj.IfcAttributes.keys():
                if obj.IfcAttributes["FlagForceBrep"] == "True":
                    brepflag = True
                    
        # getting the representation
        representation,placement,shapetype = getRepresentation(ifcfile,context,obj,forcebrep=(brepflag or FORCEBREP))
        
        if DEBUG: print str(count).ljust(3)," : ", ifctype, " (",shapetype,") : ",name

        # setting the arguments
        args = [uid,history,name,description,None,placement,representation,None]
        if ifctype in ["IfcSlab","IfcFooting","IfcRoof"]:
            args = args + ["NOTDEFINED"]
        elif ifctype in ["IfcWindow","IfcDoor"]:
            args = args + [obj.Width.Value/1000.0, obj.Height.Value/1000.0]
        elif ifctype == "IfcSpace":
            args = args + ["ELEMENT","INTERNAL",obj.Shape.BoundBox.ZMin/1000.0]
        elif ifctype == "IfcBuildingElementProxy":
            args = args + ["ELEMENT"]
        elif ifctype == "IfcSite":
            latitude = None
            longitude = None
            elevation = None
            landtitlenumber = None
            address = None
            args = args + ["ELEMENT",latitude,longitude,elevation,landtitlenumber,address]
        elif ifctype == "IfcBuilding":
            args = args + ["ELEMENT",None,None,None]
        elif ifctype == "IfcBuildingStorey":
            args = args + ["ELEMENT",obj.Placement.Base.z]
            
        # creating the product
        product = getattr(ifcfile,"create"+ifctype)(*args)
        products[obj.Name] = product
            
        # additions
        if hasattr(obj,"Additions") and (shapetype == "extrusion"):
            for o in obj.Additions:
                r2,p2,c2 = getRepresentation(ifcfile,context,o,forcebrep=True)
                if DEBUG: print "      adding ",c2," : ",str(o.Label)
                prod2 = ifcfile.createIfcBuildingElementProxy(ifcopenshell.guid.compress(uuid.uuid1().hex),history,str(o.Label),None,None,p2,r2,None,"ELEMENT")
                ifcfile.createIfcRelAggregates(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'Addition','',product,[prod2])
        
        # subtractions
        if hasattr(obj,"Subtractions") and (shapetype == "extrusion"):
            for o in obj.Subtractions:
                r2,p2,c2 = getRepresentation(ifcfile,context,o,forcebrep=True,subtraction=True)
                if DEBUG: print "      subtracting ",c2," : ",str(o.Label)
                prod2 = ifcfile.createIfcOpeningElement(ifcopenshell.guid.compress(uuid.uuid1().hex),history,str(o.Label),None,None,p2,r2,None)
                ifcfile.createIfcRelVoidsElement(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'Subtraction','',product,prod2)
                
        # properties
        if hasattr(obj,"IfcAttributes"):
            props = []
            for key in obj.IfcAttributes:
                if not (key in ["IfcUID","FlagForceBrep"]):
                    r = obj.IfcAttributes[key].strip(")").split("(")
                    if len(r) == 1:
                        tp = "IfcText"
                        val = r[0]
                    else:
                        tp = r[0]
                        val = "(".join(r[1:])
                        val = val.strip("'")
                        val = val.strip('"')
                        if DEBUG: print "      property ",key," : ",str(val), " (", str(tp), ")"
                        if tp in ["IfcLabel","IfcText","IfcIdentifier"]:
                            val = str(val)
                        elif tp == "IfcBoolean":
                            if val == ".T.":
                                val = True
                            else:
                                val = False
                        elif tp == "IfcInteger":
                            val = int(val)
                        else:
                            val = float(val)
                    props.append(ifcfile.createIfcPropertySingleValue(str(key),None,ifcfile.create_entity(str(tp),val),None))
            if props:
                pset = ifcfile.createIfcPropertySet(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'PropertySet',None,props)
                ifcfile.createIfcRelDefinesByProperties(ifcopenshell.guid.compress(uuid.uuid1().hex),history,None,None,[product],pset)
                        
        count += 1
        
    # relationships
    sites = []
    buildings = []
    floors = []
    for site in Draft.getObjectsOfType(objectslist,"Site"):
        for building in Draft.getObjectsOfType(site.Group,"Building"):
            for floor in Draft.getObjectsOfType(building.Group,"Floor"):
                children = Draft.getGroupContents(floor,walls=True)
                children = Arch.pruneIncluded(children)
                children = [products[c.Name] for c in children if c.Name in products.keys()]
                floor = products[floor.Name]
                ifcfile.createIfcRelContainedInSpatialStructure(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'StoreyLink','',children,floor)
                floors.append(floor)
            building = products[building.Name]
            if floors:
                ifcfile.createIfcRelAggregates(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'BuildingLink','',building,floors)                
            buildings.append(building)
        site = products[site.Name]
        if buildings:
            ifcfile.createIfcRelAggregates(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'SiteLink','',site,buildings)
        sites.append(site)
    if not sites:
        if DEBUG: print "adding default site"
        sites = [ifcfile.createIfcSite(ifcopenshell.guid.compress(uuid.uuid1().hex),history,"Default Site",'',None,None,None,None,"ELEMENT",None,None,None,None,None)]
    ifcfile.createIfcRelAggregates(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'ProjectLink','',project,sites)
    if not buildings:
        if DEBUG: print "adding default building"
        buildings = [ifcfile.createIfcBuilding(ifcopenshell.guid.compress(uuid.uuid1().hex),history,"Default Building",'',None,None,None,None,"ELEMENT",None,None,None)]
        ifcfile.createIfcRelAggregates(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'SiteLink','',sites[0],buildings)
        ifcfile.createIfcRelContainedInSpatialStructure(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'BuildingLink','',products.values(),buildings[0])


    if DEBUG: print "writing ",filename,"..."
    ifcfile.write(filename)
Ejemplo n.º 32
0
import ifcopenshell

model = ifcopenshell.open('model\Duplex_A_20110907.ifc')

# this just gets you the entity, defined here as wall
# feel free to change this to your needs
wall = model.by_type('IfcWall')[0]
for definition in wall.IsDefinedBy:
    # To support IFC2X3, we need to filter our results.
    if definition.is_a('IfcRelDefinesByProperties'):
        property_set = definition.RelatingPropertyDefinition
        # Might return Pset_WallCommon
        print(property_set.Name)

# ###################### end of example ###########################
Ejemplo n.º 33
0
 def __init__(self, fn):
     p = os.path.join("intermediate_files", "%s.__cache__" % os.path.basename(fn))
     if not os.path.exists(p):
         os.mkdir(p)
     self.dirname = p
     self.file = ifcopenshell.open(fn)
Ejemplo n.º 34
0
#                                                                             #
# You should have received a copy of the Lesser GNU General Public License    #
# along with this program. If not, see <http://www.gnu.org/licenses/>.        #
#                                                                             #
###############################################################################

# Some basic tests. Currently only covering basic I/O.

import os
import uuid

import ifcopenshell
import ifcopenshell.geom
import ifcopenshell.guid

f = ifcopenshell.open("input/acad2010_walls.ifc")

# Some operations on ifcopenshell.file
assert f[1].is_a("IfcCartesianPoint")
assert f[1].is_a("IfcRepresentationItem")
assert f[1].is_a() == "IfcCartesianPoint"
assert f.by_id(1).is_a("IfcCartesianPoint")
assert f["28pa2ppDf1IA$BaQrvAf48"].is_a("IfcProject")
assert f.by_guid("28pa2ppDf1IA$BaQrvAf48").is_a("IfcProject")
assert f.createIfcCartesianPoint((0., 0., 0.)).is_a("IfcCartesianPoint")
assert f.by_type("IfcProject")[0].is_a("IfcProject")
assert f.traverse(f[16])[-1].is_a("IFCSIUNIT")
assert len(f.traverse(f[35], 1)) == 2
assert len(f.traverse(f[35])) == 3
assert f[16] in f.get_inverse(f[15])
assert f[16].UnitComponent is not None
if os.path.exists(HDF_FN):
    os.unlink(HDF_FN)
f = h5py.File(HDF_FN, "w")

# Some attributes are ignored in order to prevent vlen attributes, which would render entities to have to be emulated
ignored = [('IfcPointCloud', 'Attributes'), ('IfcGrid', 'WAxes')]
# Some attributes are artificially set to have a fixed length, in order to prevent the aforementioned
fixed_length = {('IfcCartesianPoint', 'Coordinates'): 3,
                ('IfcDirection', 'DirectionRatios'): 3,
                ('IfcProductDefinitionShape', 'Representations'): 1,
                ('IfcShapeRepresentation', 'Items'): 1,
                ('IfcRelAssignsToProduct', 'RelatedObjects'): 1}
xref = [('IfcGridOffsetList', 'Offsets'),
        ('IfcGrid', 'UAxes'),
        ('IfcGrid', 'VAxes')]
precision = 32 if SINGLE_PRECISION else 64
mapping = hdf5_mapping.hdf5_mapping(ifc.schema, f, ignore=ignored, fix_length=fixed_length, force_xref=xref, precision=precision)

print "Reading SPF data"

ifcf = ifcopenshell.open(IFC_FN)

print "Creating HDF5 instance population"

mapping.create_population("Haus30_population", ifcf, compressed=USE_COMPRESSION)

f.close()

print "Done :)"
Ejemplo n.º 36
0
 def get_file():
     if IfcStore.file is None:
         IfcStore.path = bpy.context.scene.BIMProperties.ifc_file
         IfcStore.file = ifcopenshell.open(IfcStore.path)
     return IfcStore.file
Ejemplo n.º 37
0
                props = dict(filter(None, map(self.process, getattr(i, attribute_name))))
                if not i.is_a("IfcObject"):
                    props = i.Name, props
                self.cache[id] = props
                return props

    def __iter__(self):
        for object in self.file.by_type("IfcObject"):
            yield object.GlobalId, self[object]

if __name__ == "__main__":
    import sys
    import pprint

    filepath = "models/Office_A_20110811.ifc"
    print("Opening IFC file %s" % filepath, file=sys.stderr)
    ifc_file = ifcopenshell.open(filepath)
    print("file opened.", file=sys.stderr)

    metadata = metadata_dictionary(ifc_file)

    for product in ifc_file.by_type("IfcProduct"):
        print(product)
        print("=" * 20)
        pprint.pprint(metadata[product])
        print()

    # Alternatively, convert to a dict directly
    d = dict(metadata)
    pprint.pprint(d)
Ejemplo n.º 38
0
        p6xer.file = ifcfile
        p6xer.execute()
    else:
        raise Exception("No files provided for output")
elif args.schedule == "mspxml":
    msp = MSP2Ifc()
    msp.xml = args.file()
    msp.output = args.output
    ifcfile = get_file()
    if ifcfile:
        msp.file = ifcfile
        msp.execute()
elif args.schedule == "p6xml":
    p6xml = P62Ifc()
    p6xml.output = args.output
    p6xml.xml = args.file
    ifcfile = get_file()
    if ifcfile:
        p6xml.file = ifcopenshell.open(args.ifcfile)
        p6xml.execute()
elif args.schedule == "pp":
    pp = PP2Ifc()
    pp.output = args.output
    pp.pp = args.file
    ifcfile = get_file()
    if ifcfile:
        pp.file = ifcopenshell.open(args.ifcfile)
        pp.execute()
else:
    print("schedule type you selected is not implemented at the moment")
Ejemplo n.º 39
0
def insert(filename,docname,skip=[]):
    "imports the contents of an IFC file"
    
    p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch")
    DEBUG = p.GetBool("ifcDebug",False)
    PREFIX_NUMBERS = p.GetBool("ifcPrefixNumbers",False)
    SKIP = p.GetString("ifcSkip","")
    SEPARATE_OPENINGS = p.GetBool("ifcSeparateOpenings",False)
    
    try:
        import ifcopenshell
    except:
        FreeCAD.Console.PrintError("IfcOpenShell was not found on this system. IFC support is disabled\n")
        return

    if DEBUG: print "opening ",filename,"..."
    try:
        doc = FreeCAD.getDocument(docname)
    except:
        doc = FreeCAD.newDocument(docname)
    FreeCAD.ActiveDocument = doc
    
    global ifcfile # keeping global for debugging purposes
    if isinstance(filename,unicode): 
        import sys #workaround since ifcopenshell currently can't handle unicode filenames
        filename = filename.encode(sys.getfilesystemencoding())
    ifcfile = ifcopenshell.open(filename)
    from ifcopenshell import geom
    settings = ifcopenshell.geom.settings()
    settings.set(settings.USE_BREP_DATA,True)
    settings.set(settings.SEW_SHELLS,True)
    settings.set(settings.USE_WORLD_COORDS,True)
    if SEPARATE_OPENINGS: 
        settings.set(settings.DISABLE_OPENING_SUBTRACTIONS,True)
    sites = ifcfile.by_type("IfcSite")
    buildings = ifcfile.by_type("IfcBuilding")
    floors = ifcfile.by_type("IfcBuildingStorey")
    products = ifcfile.by_type("IfcProduct")
    openings = ifcfile.by_type("IfcOpeningElement")
    annotations = ifcfile.by_type("IfcAnnotation")

    # building relations tables
    objects = {} # { id:object, ... }
    additions = {} # { host:[child,...], ... }
    subtractions = [] # [ [opening,host], ... ]
    properties = {} # { host:[property, ...], ... }
    for r in ifcfile.by_type("IfcRelContainedInSpatialStructure"):
        additions.setdefault(r.RelatingStructure.id(),[]).extend([e.id() for e in r.RelatedElements])
    for r in ifcfile.by_type("IfcRelAggregates"):
        additions.setdefault(r.RelatingObject.id(),[]).extend([e.id() for e in r.RelatedObjects])
    for r in ifcfile.by_type("IfcRelVoidsElement"):
        subtractions.append([r.RelatedOpeningElement.id(), r.RelatingBuildingElement.id()])
    for r in ifcfile.by_type("IfcRelDefinesByProperties"):
        for obj in r.RelatedObjects:
            if r.RelatingPropertyDefinition.is_a("IfcPropertySet"):
                properties.setdefault(obj.id(),[]).extend([e.id() for e in r.RelatingPropertyDefinition.HasProperties])
    count = 0

    # products
    for product in products:
        pid = product.id()
        guid = product.GlobalId
        ptype = product.is_a()
        name = product.Name or str(ptype[3:])
        if PREFIX_NUMBERS: name = "ID" + str(pid) + " " + name
        obj = None
        baseobj = None
        brep = None
        
        if (ptype == "IfcOpeningElement") and (not SEPARATE_OPENINGS): continue
        if pid in skip: continue # user given id skip list
        if ptype in SKIP: continue # preferences-set type skip list
        try:
            cr = ifcopenshell.geom.create_shape(settings,product)
            brep = cr.geometry.brep_data
        except:
            pass
        if brep:
            shape = Part.Shape()
            shape.importBrepFromString(brep)
            shape.scale(1000.0) # IfcOpenShell always outputs in meters
            if not shape.isNull():
                baseobj = FreeCAD.ActiveDocument.addObject("Part::Feature",name+"_body")
                baseobj.Shape = shape
        for freecadtype,ifctypes in typesmap.iteritems():
            if ptype in ifctypes:
                obj = getattr(Arch,"make"+freecadtype)(baseobj=baseobj,name=name)
                obj.Label = name
                # setting role
                try:
                    r = ptype[3:]
                    tr = dict((v,k) for k, v in translationtable.iteritems())
                    if r in tr.keys():
                        r = tr[r]
                    # remove the "StandardCase"
                    if "StandardCase" in r:
                        r = r[:-12]
                    obj.Role = r
                except:
                    pass
                # setting uid
                if hasattr(obj,"IfcAttributes"):
                    a = obj.IfcAttributes
                    a["IfcUID"] = str(guid)
                    obj.IfcAttributes = a
                break
        if not obj:
            obj = baseobj
        if obj:
            sh = baseobj.Shape.ShapeType if hasattr(baseobj,"Shape") else "None"
            sols = str(baseobj.Shape.Solids) if hasattr(baseobj,"Shape") else ""
            pc = str(int((float(count)/(len(products)+len(annotations))*100)))+"% "
            if DEBUG: print pc,"creating object ",pid," : ",ptype, " with shape: ",sh," ",sols
            objects[pid] = obj
            
        # properties
        if pid in properties:
            if hasattr(obj,"IfcAttributes"):
                a = obj.IfcAttributes
                for p in properties[pid]:
                    o = ifcfile[p]
                    if o.is_a("IfcPropertySingleValue"):
                        a[o.Name] = str(o.NominalValue)
                obj.IfcAttributes = a
        count += 1
        
    FreeCAD.ActiveDocument.recompute()
        
    if DEBUG: print "Processing relationships..."
            
    # subtractions
    if SEPARATE_OPENINGS:
        for subtraction in subtractions:
            if (subtraction[0] in objects.keys()) and (subtraction[1] in objects.keys()):
                #print objects[subtraction[0]].Name, objects[subtraction[1]].Name
                Arch.removeComponents(objects[subtraction[0]],objects[subtraction[1]])
                
    # additions
    for host,children in additions.iteritems():
        if host in objects.keys():
            cobs = [objects[child] for child in children if child in objects.keys()]
            if cobs:
                Arch.addComponents(cobs,objects[host])
                
    FreeCAD.ActiveDocument.recompute()
        
    # cleaning bad shapes
    for obj in objects.values():
        if obj.isDerivedFrom("Part::Feature"):
            if obj.Shape.isNull():
                Arch.rebuildArchShape(obj)
                
    FreeCAD.ActiveDocument.recompute()
    
    # 2D elements
    
    if DEBUG and annotations: print "Creating 2D geometry..."
    
    for annotation in annotations:
        aid = annotation.id()
        if aid in skip: continue # user given id skip list
        if "IfcAnnotation" in SKIP: continue # preferences-set type skip list
        name = "Annotation"
        if annotation.Name: name = annotation.Name
        if PREFIX_NUMBERS: name = "ID" + str(aid) + " " + name
        shapes2d = []
        for repres in annotation.Representation.Representations:
            shapes2d.extend(setRepresentation(repres))
        if shapes2d:
            sh = Part.makeCompound(shapes2d)
            pc = str(int((float(count)/(len(products)+len(annotations))*100)))+"% "
            if DEBUG: print pc,"creating object ",aid," : Annotation with shape: ",sh
            o = FreeCAD.ActiveDocument.addObject("Part::Feature",name)
            o.Shape = sh
        count += 1
        
    FreeCAD.ActiveDocument.recompute()
    
    if FreeCAD.GuiUp:
        import FreeCADGui
        FreeCADGui.SendMsgToActiveView("ViewFit")
    return doc
Ejemplo n.º 40
0
import json
import ifcopenshell
import ifcopenshell.geom

with open("output.json", 'r') as f:
    load_dict = json.load(f)

clash_guids = load_dict[0]['clashes'].keys()
set_clash_guids = set(i for i in clash_guids)
filename1 = "1.ifc"
ifc_file = ifcopenshell.open(filename1)

final_id = set()
for id in set_clash_guids:
    a, b = id.split('-')
    final_id.add(a)
    final_id.add(b)

a = ifc_file[final_id.pop()]

s = ifcopenshell.geom.settings()
s.set(s.USE_PYTHON_OPENCASCADE, True)
viewer = ifcopenshell.geom.utils.initialize_display()
viewer.set_bg_gradient_color([255, 255, 255], [255, 255, 255])

all_guids = set(i.GlobalId for i in ifc_file.by_type("IfcProduct"))

for id in all_guids:
    entity = ifc_file[id]
    if id in final_id:
        clr = (1, 0, 0)
Ejemplo n.º 41
0
 def load(self, fn):
     if fn in self.files: return        
     f = ifcopenshell.open(fn)
     self.files[fn] = f
     for c in self.components:
         c.load_file(f, setting=self.settings)
Ejemplo n.º 42
0
import ifcopenshell
import xlsxwriter  # https://xlsxwriter.readthedocs.io/tutorial01.html#tutorial1

# this line opens the workbook, if it doesn't exist it makes it, otherwise
# it will overwrite the existing file.
# if it dpes already exist please close it otherwise it will not work (it cannot read open files)
workbook = xlsxwriter.Workbook('output/future_format.xlsx')
# you have the workbook open, now specify the sheet you want to write to
worksheet = workbook.add_worksheet()
# this is extra code that you can include to format the cells in your document. You could shange this to other examples. to create other effects.
bold = workbook.add_format({'bold': True})

# this line loads the ifc model into python. - careful most internet examples use ifc_model,
# but we are using model here, so that it also works in RWTH viewer.
# When RWTH viewer loads the model in the GUI it calls it model.
model = ifcopenshell.open("model/Duplex_A_20110907.ifc")

# this is normally formatted
worksheet.write(0, 0, 'hello')

# in this line we have added the bold argument defined previously with the add_format command to define the format of the cell.
worksheet.write(0, 0, 'hello', bold)

# when you have finished editing the document it is essential to close the workbook.
# these saves the document.
workbook.close()
Ejemplo n.º 43
0
def export(exportList,filename):
    "exports FreeCAD contents to an IFC file"
    
    try:
        global ifcopenshell
        import ifcopenshell
    except:
        if DEBUG: print "using legacy exporter"
        import importIFClegacy
        return importIFClegacy.export(exportList,filename)

    p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch")
    FORCEBREP = p.GetBool("ifcExportAsBrep",False)
    DEBUG = p.GetBool("ifcDebug",False)
    version = FreeCAD.Version()
    owner = FreeCAD.ActiveDocument.CreatedBy
    email = ''
    if ("@" in owner) and ("<" in owner):
        s = owner.split("<")
        owner = s[0]
        email = s[1].strip(">")
    global ifctemplate
    ifctemplate = ifctemplate.replace("$version",version[0]+"."+version[1]+" build "+version[2])
    ifctemplate = ifctemplate.replace("$owner",owner)
    ifctemplate = ifctemplate.replace("$company",FreeCAD.ActiveDocument.Company)
    ifctemplate = ifctemplate.replace("$email",email)
    ifctemplate = ifctemplate.replace("$now",str(int(time.time())))
    ifctemplate = ifctemplate.replace("$projectid",FreeCAD.ActiveDocument.Uid[:22].replace("-","_"))
    ifctemplate = ifctemplate.replace("$project",FreeCAD.ActiveDocument.Name)
    ifctemplate = ifctemplate.replace("$filename",filename)
    ifctemplate = ifctemplate.replace("$timestamp",str(time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime())))
    template = tempfile.mkstemp(suffix=".ifc")[1]
    of = pyopen(template,"wb")
    of.write(ifctemplate)
    of.close()
    global ifcfile
    ifcfile = ifcopenshell.open(template)
    history = ifcfile.by_type("IfcOwnerHistory")[0]
    context = ifcfile.by_type("IfcGeometricRepresentationContext")[0]
    project = ifcfile.by_type("IfcProject")[0]
    objectslist = Draft.getGroupContents(exportList,walls=True,addgroups=True)
    objectslist = Arch.pruneIncluded(objectslist)
    products = {}
    count = 1
    
    # products
    for obj in objectslist:
        
        # getting generic data
        name = str(obj.Label)
        description = str(obj.Description) if hasattr(obj,"Description") else ""
            
        # getting uid
        uid = None
        if hasattr(obj,"IfcAttributes"):
            if "IfcUID" in obj.IfcAttributes.keys():
                uid = str(obj.IfcAttributes["IfcUID"])
        if not uid:
            uid = ifcopenshell.guid.compress(uuid.uuid1().hex)
            
        # setting the IFC type + name conversions
        if hasattr(obj,"Role"):
            ifctype = obj.Role.replace(" ","")
        else:
            ifctype = Draft.getType(obj)
        if ifctype == "Foundation":
            ifctype = "Footing"
        elif ifctype == "Floor":
            ifctype = "BuildingStorey"
        elif ifctype == "Rebar":
            ifctype = "ReinforcingBar"
        ifctype = "Ifc" + ifctype
        if ifctype == "IfcGroup":
            continue
        if not ifctype in ifctypes:
            ifctype = "IfcBuildingElementProxy"
        
        # getting the "Force BREP" flag
        brepflag = False
        if hasattr(obj,"IfcAttributes"):
            if "FlagForceBrep" in obj.IfcAttributes.keys():
                if obj.IfcAttributes["FlagForceBrep"] == "True":
                    brepflag = True
                    
        # getting the representation
        representation,placement,shapetype = getRepresentation(ifcfile,context,obj,forcebrep=(brepflag or FORCEBREP))
        
        if DEBUG: print str(count).ljust(3)," : ", ifctype, " (",shapetype,") : ",name

        # setting the arguments
        args = [uid,history,name,description,None,placement,representation,None]
        if ifctype in ["IfcSlab","IfcFooting","IfcRoof"]:
            args = args + ["NOTDEFINED"]
        elif ifctype in ["IfcWindow","IfcDoor"]:
            args = args + [obj.Width.Value, obj.Height.Value]
        elif ifctype == "IfcSpace":
            args = args + ["ELEMENT","INTERNAL",obj.Shape.BoundBox.ZMin]
        elif ifctype == "IfcBuildingElementProxy":
            args = args + ["ELEMENT"]
        elif ifctype == "IfcSite":
            latitude = None
            longitude = None
            elevation = None
            landtitlenumber = None
            address = None
            args = args + ["ELEMENT",latitude,longitude,elevation,landtitlenumber,address]
        elif ifctype == "IfcBuilding":
            args = args + ["ELEMENT",None,None,None]
        elif ifctype == "IfcBuildingStorey":
            args = args + ["ELEMENT",None]
            
        # creating the product
        product = getattr(ifcfile,"create"+ifctype)(*args)
        products[obj.Name] = product
            
        # additions
        if hasattr(obj,"Additions") and (shapetype == "extrusion"):
            for o in obj.Additions:
                r2,p2,c2 = getRepresentation(ifcfile,context,o,forcebrep=True)
                if DEBUG: print "      adding ",c2," : ",str(o.Label)
                prod2 = ifcfile.createIfcBuildingElementProxy(ifcopenshell.guid.compress(uuid.uuid1().hex),history,str(o.Label),None,None,p2,r2,None,"ELEMENT")
                ifcfile.createIfcRelAggregates(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'Addition','',product,[prod2])
        
        # subtractions
        if hasattr(obj,"Subtractions") and (shapetype == "extrusion"):
            for o in obj.Subtractions:
                r2,p2,c2 = getRepresentation(ifcfile,context,o,forcebrep=True,subtraction=True)
                if DEBUG: print "      subtracting ",c2," : ",str(o.Label)
                prod2 = ifcfile.createIfcOpeningElement(ifcopenshell.guid.compress(uuid.uuid1().hex),history,str(o.Label),None,None,p2,r2,None)
                ifcfile.createIfcRelVoidsElement(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'Subtraction','',product,prod2)
    
        count += 1
        
    # relationships
    sites = []
    buildings = []
    floors = []
    for site in Draft.getObjectsOfType(objectslist,"Site"):
        for building in Draft.getObjectsOfType(site.Group,"Building"):
            for floor in Draft.getObjectsOfType(building.Group,"Floor"):
                children = Draft.getGroupContents(floor,walls=True)
                children = Arch.pruneIncluded(children)
                children = [products[c.Name] for c in children if c.Name in products.keys()]
                floor = products[floor.Name]
                ifcfile.createIfcRelContainedInSpatialStructure(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'StoreyLink','',children,floor)
                floors.append(floor)
            building = products[building.Name]
            if floors:
                ifcfile.createIfcRelAggregates(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'BuildingLink','',building,floors)                
            buildings.append(building)
        site = products[site.Name]
        if buildings:
            ifcfile.createIfcRelAggregates(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'SiteLink','',site,buildings)
        sites.append(site)
    if not sites:
        if DEBUG: print "adding default site"
        sites = [ifcfile.createIfcSite(ifcopenshell.guid.compress(uuid.uuid1().hex),history,"Default Site",'',None,None,None,None,"ELEMENT",None,None,None,None,None)]
    ifcfile.createIfcRelAggregates(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'ProjectLink','',project,sites)
    if not buildings:
        if DEBUG: print "adding default building"
        buildings = [ifcfile.createIfcBuilding(ifcopenshell.guid.compress(uuid.uuid1().hex),history,"Default Building",'',None,None,None,None,"ELEMENT",None,None,None)]
        ifcfile.createIfcRelAggregates(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'SiteLink','',sites[0],buildings)
        ifcfile.createIfcRelContainedInSpatialStructure(ifcopenshell.guid.compress(uuid.uuid1().hex),history,'BuildingLink','',products.values(),buildings[0])


    if DEBUG: print "writing ",filename,"..."
    ifcfile.write(filename)
Ejemplo n.º 44
0
import OCC.TopoDS
import OCC.TopExp
import OCC.TopAbs

import ifcopenshell
import ifcopenshell.geom

# Specify to return pythonOCC shapes from ifcopenshell.geom.create_shape()
settings = ifcopenshell.geom.settings()
settings.set(settings.USE_PYTHON_OPENCASCADE, True)

# Initialize a graphical display window
occ_display = ifcopenshell.geom.utils.initialize_display()

# Open the IFC file using IfcOpenShell
ifc_file = ifcopenshell.open("IfcOpenHouse.ifc")

# Display the geometrical contents of the file using Python OpenCascade
products = ifc_file.by_type("IfcProduct")
for product in products:
    if product.is_a("IfcOpeningElement"): continue
    if product.Representation:
        shape = ifcopenshell.geom.create_shape(settings, product).geometry
        display_shape = ifcopenshell.geom.utils.display_shape(shape)
        if product.is_a("IfcPlate"):
            # Plates are the transparent parts of the window assembly
            # in the IfcOpenHouse model
            ifcopenshell.geom.utils.set_shape_transparency(display_shape, 0.8)

# Wait for user input and erase the display
raw_input()
Ejemplo n.º 45
0
def insert(filename,docname,skip=[]):
    "imports the contents of an IFC file"
    
    import ifcopenshell
    print " "
    print "opening ",filename,"..."
    try:
        doc = FreeCAD.getDocument(docname)
    except:
        doc = FreeCAD.newDocument(docname)
    FreeCAD.ActiveDocument = doc
    
    print 'We gone use importIFCmin importer!'

    global ifcfile # keeping global for debugging purposes
    ifcopenshell.clean()
    if isinstance(filename,unicode):
      import sys #workaround since ifcopenshell currently can't handle unicode filenames
      filename=filename.encode(sys.getfilesystemencoding())
    ifcfile = ifcopenshell.open(filename)
    shape_attributes = ifcopenshell.SEW_SHELLS
    products = ifcfile.by_type("IfcProduct")
    objects = {} # { id:object, ... }

    # products
    for pno, product in enumerate(products):
        pid = product.id()
        ptype = product.is_a()
        print "Product ",pno," of ",len(products)," is Entity #",pid,"= ",ptype,
        name = "ID" + str(pid)
        obj = None
        baseobj = None
        
        if (ptype == "IfcOpeningElement"): 
          print "Entity ",pno," of ",len(products),", IfcOpeningElement: is computed with parent",
          continue
        if pid in skip: continue
        
        brep = ifcopenshell.create_shape(product,shape_attributes)
        if brep:
            shape = Part.Shape()
            shape.importBrepFromString(brep)
            if not shape.isNull():
                baseobj = FreeCAD.ActiveDocument.addObject("Part::Feature",name+"_body")
                baseobj.Shape = shape
        else:
          print "                     ifcos:  no shape",
        if not obj:
            obj = baseobj
        if obj:
            sh = baseobj.Shape.ShapeType if hasattr(baseobj,"Shape") else "None"
            sols = str(baseobj.Shape.Solids) if hasattr(baseobj,"Shape") else ""
            print "                     creating object #",pid," with shape: ",sh," ",sols,
            objects[pid] = obj
        print " "

    print " "
    FreeCAD.ActiveDocument.recompute()
    
    # cleaning bad shapes
    for obj in objects.values():
        if obj.isDerivedFrom("Part::Feature"):
            if obj.Shape.isNull():
                print "cleaning bad shape of object: #",pid 
                Arch.rebuildArchShape(obj)
    FreeCAD.ActiveDocument.recompute()
    
    if FreeCAD.GuiUp:
        import FreeCADGui
        FreeCADGui.activeDocument().activeView().viewAxometric()
        FreeCADGui.SendMsgToActiveView("ViewFit")
    return doc
Ejemplo n.º 46
0
import os
import lxml
import uuid
import ifcopenshell

from lxml import etree as ET
from datetime import datetime
from collections import defaultdict
#from builtins import list

ifcfile = ifcopenshell.open(
    'C:\\Users\\CClaus\\Desktop\\Flat 11\\ruimtemodel_flat_11.ifc')

products = ifcfile.by_type('IfcProduct')
zones = ifcfile.by_type('IfcZone')
spaces = ifcfile.by_type('IfcSpace')
building_stories = ifcfile.by_type('IfcBuildingStorey')

#create building storey list
building_storey_list = []

for i in building_stories:
    building_storey_list.append(i.Name)

now = datetime.now()
year = now.strftime("%Y")
month = now.strftime("%m")
day = now.strftime("%d")


def create_xml(file_name, building_storey, zone):