Spaces:
Runtime error
Runtime error
File size: 11,365 Bytes
e6be672 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | # 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 <https://www.gnu.org/licenses/>.
"""
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"<Element(id={self.id}, type='{self.ifc_type}', name='{self.name}')>"
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 |