# Copyright (C) 2026 Mattia Zatelli
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see .
"""
Element model for storing IFC element information
"""
import enum
from typing import Dict, Any, List, Optional
from sqlalchemy import Column, Integer, String, Text, JSON, Float, Boolean, ForeignKey, Index
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from sqlalchemy import DateTime
import uuid
from app.core.database import Base
class ElementType(str, enum.Enum):
"""Common IFC element types"""
WALL = "IfcWall"
SLAB = "IfcSlab"
BEAM = "IfcBeam"
COLUMN = "IfcColumn"
DOOR = "IfcDoor"
WINDOW = "IfcWindow"
STAIR = "IfcStair"
RAILING = "IfcRailing"
ROOF = "IfcRoof"
SPACE = "IfcSpace"
BUILDING_ELEMENT_PROXY = "IfcBuildingElementProxy"
FURNITURE = "IfcFurniture"
COVERING = "IfcCovering"
CURTAIN_WALL = "IfcCurtainWall"
PLATE = "IfcPlate"
MEMBER = "IfcMember"
FOOTING = "IfcFooting"
PILE = "IfcPile"
OTHER = "Other"
class Element(Base):
"""
IFC Element model
Stores information about individual IFC elements
"""
__tablename__ = "elements"
# Primary key
id = Column(Integer, primary_key=True, index=True)
# External identifiers
ifc_global_id = Column(String(22), nullable=False, index=True, unique=True) # IFC GUID
project_id = Column(Integer, ForeignKey("projects.id", ondelete="CASCADE"), nullable=False, index=True)
# Element classification
ifc_type = Column(String(100), nullable=False, index=True)
element_type = Column(String(50), nullable=True, index=True) # Normalized type
ifc_class = Column(String(100), nullable=True) # Full IFC class name
# Identifiers and labels
name = Column(String(255), nullable=True, index=True)
description = Column(Text, nullable=True)
tag = Column(String(100), nullable=True, index=True)
# Spatial hierarchy
level_name = Column(String(100), nullable=True, index=True) # Storey/Floor
level_elevation = Column(Float, nullable=True)
building_name = Column(String(100), nullable=True)
site_name = Column(String(100), nullable=True)
# Geometric properties
bounding_box = Column(JSON, nullable=True) # {min: [x,y,z], max: [x,y,z]}
centroid = Column(JSON, nullable=True) # [x, y, z]
# Calculated properties
area = Column(Float, nullable=True) # Square meters
volume = Column(Float, nullable=True) # Cubic meters
length = Column(Float, nullable=True) # Linear meters
width = Column(Float, nullable=True) # Meters
height = Column(Float, nullable=True) # Meters
perimeter = Column(Float, nullable=True) # Linear meters
# Material properties
material_name = Column(String(200), nullable=True, index=True)
material_category = Column(String(100), nullable=True, index=True)
material_properties = Column(JSON, nullable=True)
# Classification and properties
properties = Column(JSON, nullable=True) # All IFC properties as key-value pairs
quantities = Column(JSON, nullable=True) # IFC quantities
classifications = Column(JSON, nullable=True) # External classifications (Uniclass, etc.)
# Relationships
parent_element_id = Column(Integer, ForeignKey("elements.id"), nullable=True, index=True)
assembly_id = Column(String(100), nullable=True, index=True) # Assembly identifier
# Status flags
has_geometry = Column(Boolean, default=False)
has_properties = Column(Boolean, default=False)
has_materials = Column(Boolean, default=False)
is_external = Column(Boolean, nullable=True)
is_load_bearing = Column(Boolean, nullable=True)
# Fire safety properties
fire_rating = Column(String(50), nullable=True, index=True)
combustible = Column(Boolean, nullable=True)
# Acoustic properties
acoustic_rating = Column(String(50), nullable=True)
# Thermal properties
thermal_transmittance = Column(Float, nullable=True) # U-value
thermal_mass = Column(Float, nullable=True)
# Timestamps
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
# Relationships
project = relationship("Project", back_populates="elements")
parent_element = relationship("Element", remote_side=[id])
child_elements = relationship("Element", back_populates="parent_element")
query_results = relationship("QueryResult", back_populates="element", cascade="all, delete-orphan")
# Indexes for performance
__table_args__ = (
Index('idx_elements_project_type', 'project_id', 'ifc_type'),
Index('idx_elements_level', 'project_id', 'level_name'),
Index('idx_elements_material', 'project_id', 'material_name'),
Index('idx_elements_spatial', 'project_id', 'building_name', 'level_name'),
Index('idx_elements_properties', 'project_id', 'has_geometry', 'has_properties'),
)
def __repr__(self):
return f""
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary for API responses"""
return {
"id": f"el_{self.id}",
"ifc_global_id": self.ifc_global_id,
"ifc_type": self.ifc_type,
"element_type": self.element_type,
"name": self.name,
"description": self.description,
"tag": self.tag,
"level_name": self.level_name,
"level_elevation": self.level_elevation,
"building_name": self.building_name,
"bounding_box": self.bounding_box,
"centroid": self.centroid,
"area": self.area,
"volume": self.volume,
"length": self.length,
"width": self.width,
"height": self.height,
"material_name": self.material_name,
"material_category": self.material_category,
"properties": self.properties or {},
"quantities": self.quantities or {},
"classifications": self.classifications or {},
"has_geometry": self.has_geometry,
"has_properties": self.has_properties,
"has_materials": self.has_materials,
"is_external": self.is_external,
"is_load_bearing": self.is_load_bearing,
"fire_rating": self.fire_rating,
"thermal_transmittance": self.thermal_transmittance,
}
def get_summary(self) -> Dict[str, Any]:
"""Get element summary for listings"""
return {
"id": f"el_{self.id}",
"ifc_global_id": self.ifc_global_id,
"ifc_type": self.ifc_type,
"name": self.name,
"level_name": self.level_name,
"area": self.area,
"volume": self.volume,
"material_name": self.material_name,
"bounding_box": self.bounding_box,
}
@classmethod
def get_public_id(cls, internal_id: int) -> str:
"""Convert internal ID to public format"""
return f"el_{internal_id}"
@classmethod
def parse_public_id(cls, public_id: str) -> Optional[int]:
"""Parse public ID to internal ID"""
if not public_id.startswith("el_"):
return None
try:
return int(public_id[3:])
except ValueError:
return None
def normalize_element_type(self) -> str:
"""Normalize IFC type to standard categories"""
type_mapping = {
"IfcWall": "Wall",
"IfcWallStandardCase": "Wall",
"IfcSlab": "Floor",
"IfcBeam": "Beam",
"IfcColumn": "Column",
"IfcDoor": "Door",
"IfcWindow": "Window",
"IfcStair": "Stair",
"IfcStairFlight": "Stair",
"IfcRailing": "Railing",
"IfcRoof": "Roof",
"IfcSpace": "Space",
"IfcRoom": "Room",
"IfcFurniture": "Furniture",
"IfcCovering": "Covering",
"IfcCurtainWall": "Curtain Wall",
"IfcPlate": "Plate",
"IfcMember": "Member",
"IfcFooting": "Foundation",
"IfcPile": "Pile",
}
return type_mapping.get(self.ifc_type, "Other")
def get_property_value(self, property_name: str) -> Any:
"""Get specific property value"""
if not self.properties:
return None
return self.properties.get(property_name)
def set_property_value(self, property_name: str, value: Any):
"""Set specific property value"""
if not self.properties:
self.properties = {}
self.properties[property_name] = value
def get_classification(self, system: str) -> Optional[str]:
"""Get classification by system (e.g., 'Uniclass', 'OmniClass')"""
if not self.classifications:
return None
return self.classifications.get(system)
def has_fire_rating(self) -> bool:
"""Check if element has fire rating"""
return bool(self.fire_rating and self.fire_rating != "None")
def is_structural(self) -> bool:
"""Check if element is structural"""
structural_types = {
"IfcWall", "IfcBeam", "IfcColumn", "IfcSlab",
"IfcFooting", "IfcPile", "IfcMember"
}
return self.ifc_type in structural_types or self.is_load_bearing == True
def get_area_by_type(self) -> Optional[float]:
"""Get area based on element type (wall area, floor area, etc.)"""
if self.ifc_type in ["IfcWall", "IfcCurtainWall"]:
return self.area # Wall area
elif self.ifc_type in ["IfcSlab", "IfcSpace", "IfcRoom"]:
return self.area # Floor area
elif self.ifc_type in ["IfcWindow", "IfcDoor"]:
return self.area # Opening area
return self.area
def calculate_carbon_footprint(self) -> Optional[float]:
"""Calculate approximate carbon footprint (if material data available)"""
# This would integrate with material carbon databases
# Placeholder implementation
if not self.volume or not self.material_name:
return None
# Simple carbon factors (kg CO2e per m3)
carbon_factors = {
"Concrete": 400,
"Steel": 2500,
"Timber": 50,
"Brick": 300,
"Aluminum": 8000,
}
for material, factor in carbon_factors.items():
if material.lower() in (self.material_name or "").lower():
return self.volume * factor
return None