This commit is contained in:
Andrej730
2026-02-27 11:15:30 +05:00
parent 8834a51122
commit 92c979fbbf
27 changed files with 121 additions and 271 deletions
+6 -12
View File
@@ -315,24 +315,18 @@ cecho(f"* Build Directory = {BUILD_DIR}", MAGENTA)
cecho(f"* Dependency Directory = {DEPS_DIR}", MAGENTA) cecho(f"* Dependency Directory = {DEPS_DIR}", MAGENTA)
cecho(f" - The directory where {PROJECT_NAME} dependencies are installed.") cecho(f" - The directory where {PROJECT_NAME} dependencies are installed.")
cecho(f"* Build Config Type = {BUILD_CFG}", MAGENTA) cecho(f"* Build Config Type = {BUILD_CFG}", MAGENTA)
cecho( cecho(""" - The used build configuration type for the dependencies.
""" - The used build configuration type for the dependencies. Defaults to RelWithDebInfo if not specified.""")
Defaults to RelWithDebInfo if not specified."""
)
if BUILD_CFG == "MinSizeRel": if BUILD_CFG == "MinSizeRel":
cecho(" WARNING: MinSizeRel build can suffer from a significant performance loss.", RED) cecho(" WARNING: MinSizeRel build can suffer from a significant performance loss.", RED)
cecho(f"* IFCOS_NUM_BUILD_PROCS = {IFCOS_NUM_BUILD_PROCS}", MAGENTA) cecho(f"* IFCOS_NUM_BUILD_PROCS = {IFCOS_NUM_BUILD_PROCS}", MAGENTA)
cecho( cecho(""" - How many compiler processes may be run in parallel.
""" - How many compiler processes may be run in parallel. """)
"""
)
cecho(f" * IFCOS_SCHEMAS = '{os.environ.get('IFCOS_SCHEMAS')}'", MAGENTA) cecho(f" * IFCOS_SCHEMAS = '{os.environ.get('IFCOS_SCHEMAS')}'", MAGENTA)
cecho( cecho(""" - IFC Schemas to compile. If not provided, fallback to default provided in cmake.
""" - IFC Schemas to compile. If not provided, fallback to default provided in cmake. """)
"""
)
dependency_tree: "dict[str, tuple[str, ...]]" = { dependency_tree: "dict[str, tuple[str, ...]]" = {
"IfcParse": ("boost", "libxml2", "hdf5", "rocksdb"), "IfcParse": ("boost", "libxml2", "hdf5", "rocksdb"),
+2 -2
View File
@@ -34,8 +34,8 @@ client_id, client_secret = "", ""
class OAuthReceiver(http.server.BaseHTTPRequestHandler): class OAuthReceiver(http.server.BaseHTTPRequestHandler):
def do_GET(self) -> None: def do_GET(self) -> None:
query = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query) query = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
self.server.auth_code = query.get("code", [""])[0] # type:ignore self.server.auth_code = query.get("code", [""])[0] # type: ignore
self.server.auth_state = query.get("state", [""])[0] # type:ignore self.server.auth_state = query.get("state", [""])[0] # type: ignore
self.send_response(200) self.send_response(200)
self.send_header("Content-type", "text/plain") self.send_header("Content-type", "text/plain")
self.end_headers() self.end_headers()
+2 -6
View File
@@ -63,8 +63,7 @@ class BrickschemaData:
if namespace == "https://brickschema.org/schema/Brick": if namespace == "https://brickschema.org/schema/Brick":
return [] return []
results = [] results = []
query = BrickStore.graph.query( query = BrickStore.graph.query("""
"""
PREFIX brick: <https://brickschema.org/schema/Brick#> PREFIX brick: <https://brickschema.org/schema/Brick#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
@@ -81,10 +80,7 @@ class BrickschemaData:
} }
} }
GROUP BY ?object GROUP BY ?object
""".replace( """.replace("{uri}", uri))
"{uri}", uri
)
)
for row in query: for row in query:
predicate_uri = row.get("predicate") predicate_uri = row.get("predicate")
predicate_name = predicate_uri.toPython().split("#")[-1] predicate_name = predicate_uri.toPython().split("#")[-1]
@@ -335,12 +335,9 @@ class BaseLinesShader(BaseShader):
TYPE = "LINES" TYPE = "LINES"
DEF_GLSL = ( DEF_GLSL = BaseShader.DEF_GLSL + """
BaseShader.DEF_GLSL
+ """
#define GAP_SIZE {gap_size} #define GAP_SIZE {gap_size}
""" """
)
GEOM_GLSL = """ GEOM_GLSL = """
layout(lines) in; layout(lines) in;
@@ -401,13 +398,10 @@ class DotsGizmoShader(GizmoShader):
TYPE = "POINTS" TYPE = "POINTS"
DEF_GLSL = ( DEF_GLSL = BaseShader.DEF_GLSL + """
BaseShader.DEF_GLSL
+ """
#define CIRCLE_SEGMENTS 12 #define CIRCLE_SEGMENTS 12
#define CIRCLE_RADIUS 8 #define CIRCLE_RADIUS 8
""" """
)
GEOM_GLSL = """ GEOM_GLSL = """
layout(points) in; layout(points) in;
@@ -58,15 +58,13 @@ class DecorationShader:
"PLANAR LOAD", "PLANAR LOAD",
} }
if pattern not in valid_patterns: if pattern not in valid_patterns:
raise ValueError( raise ValueError("""pattern must be one of:
"""pattern must be one of:
PERPENDICULAR DISTRIBUTED FORCE PERPENDICULAR DISTRIBUTED FORCE
PARALLEL DISTRIBUTED FORCE, PARALLEL DISTRIBUTED FORCE,
DISTRIBUTED MOMENT, DISTRIBUTED MOMENT,
SINGLE FORCE, SINGLE FORCE,
SINGLE MOMENT, SINGLE MOMENT,
PLANAR LOAD""" PLANAR LOAD""")
)
if "DISTRIBUTED" in pattern.upper(): if "DISTRIBUTED" in pattern.upper():
shader = self.get_linear_shader(pattern) shader = self.get_linear_shader(pattern)
return shader return shader
-1
View File
@@ -55,7 +55,6 @@ from bonsai.bim.module.model.ui import (
from bonsai.bim.module.pset.prop import IfcProperty from bonsai.bim.module.pset.prop import IfcProperty
from bonsai.bim.prop import Attribute from bonsai.bim.prop import Attribute
if TYPE_CHECKING: if TYPE_CHECKING:
from bonsai.bim.module.project.prop import BIMProjectProperties from bonsai.bim.module.project.prop import BIMProjectProperties
from bonsai.bim.prop import ObjProperty from bonsai.bim.prop import ObjProperty
+16 -44
View File
@@ -164,17 +164,13 @@ class Brick(bonsai.core.tool.Brick):
@classmethod @classmethod
def export_brick_attributes(cls, brick_uri: str) -> dict[str, Any]: def export_brick_attributes(cls, brick_uri: str) -> dict[str, Any]:
query = BrickStore.graph.query( query = BrickStore.graph.query("""
"""
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?label { SELECT ?label {
<{brick_uri}> rdfs:label ?label . <{brick_uri}> rdfs:label ?label .
} }
LIMIT 1 LIMIT 1
""".replace( """.replace("{brick_uri}", brick_uri))
"{brick_uri}", brick_uri
)
)
name = None name = None
for row in query: for row in query:
name = str(row.get("label")) name = str(row.get("label"))
@@ -218,18 +214,14 @@ class Brick(bonsai.core.tool.Brick):
@classmethod @classmethod
def get_brickifc_project(cls) -> Union[str, None]: def get_brickifc_project(cls) -> Union[str, None]:
project = tool.Ifc.get().by_type("IfcProject")[0] project = tool.Ifc.get().by_type("IfcProject")[0]
query = BrickStore.graph.query( query = BrickStore.graph.query("""
"""
PREFIX ref: <https://brickschema.org/schema/Brick/ref#> PREFIX ref: <https://brickschema.org/schema/Brick/ref#>
SELECT ?proj WHERE { SELECT ?proj WHERE {
?proj a ref:ifcProject . ?proj a ref:ifcProject .
?proj ref:ifcProjectID "{project_globalid}" . ?proj ref:ifcProjectID "{project_globalid}" .
} }
LIMIT 1 LIMIT 1
""".replace( """.replace("{project_globalid}", project.GlobalId))
"{project_globalid}", project.GlobalId
)
)
results = list(query) results = list(query)
if results: if results:
return results[0][0].toPython() return results[0][0].toPython()
@@ -275,17 +267,13 @@ class Brick(bonsai.core.tool.Brick):
@classmethod @classmethod
def get_item_class(cls, item: str) -> Union[str, None]: def get_item_class(cls, item: str) -> Union[str, None]:
query = BrickStore.graph.query( query = BrickStore.graph.query("""
"""
PREFIX brick: <https://brickschema.org/schema/Brick#> PREFIX brick: <https://brickschema.org/schema/Brick#>
SELECT ?class WHERE { SELECT ?class WHERE {
<{item}> a ?class . <{item}> a ?class .
} }
LIMIT 1 LIMIT 1
""".replace( """.replace("{item}", item))
"{item}", item
)
)
for row in query: for row in query:
return row.get("class").toPython().split("#")[-1] return row.get("class").toPython().split("#")[-1]
@@ -308,8 +296,7 @@ class Brick(bonsai.core.tool.Brick):
@classmethod @classmethod
def import_brick_classes(cls, brick_class: str, split_screen: bool = False) -> None: def import_brick_classes(cls, brick_class: str, split_screen: bool = False) -> None:
query = BrickStore.graph.query( query = BrickStore.graph.query("""
"""
PREFIX brick: <https://brickschema.org/schema/Brick#> PREFIX brick: <https://brickschema.org/schema/Brick#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
@@ -322,10 +309,7 @@ class Brick(bonsai.core.tool.Brick):
} }
GROUP BY ?group GROUP BY ?group
ORDER BY asc(?group) ORDER BY asc(?group)
""".replace( """.replace("{brick_class}", brick_class))
"{brick_class}", brick_class
)
)
props = tool.Brick.get_brick_props() props = tool.Brick.get_brick_props()
if split_screen: if split_screen:
bricks = props.split_screen_bricks bricks = props.split_screen_bricks
@@ -342,8 +326,7 @@ class Brick(bonsai.core.tool.Brick):
@classmethod @classmethod
def import_brick_items(cls, brick_class: str, split_screen: bool = False) -> None: def import_brick_items(cls, brick_class: str, split_screen: bool = False) -> None:
query = BrickStore.graph.query( query = BrickStore.graph.query("""
"""
PREFIX brick: <https://brickschema.org/schema/Brick#> PREFIX brick: <https://brickschema.org/schema/Brick#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
@@ -354,10 +337,7 @@ class Brick(bonsai.core.tool.Brick):
} }
} }
ORDER BY asc(?item) ORDER BY asc(?item)
""".replace( """.replace("{brick_class}", brick_class))
"{brick_class}", brick_class
)
)
props = tool.Brick.get_brick_props() props = tool.Brick.get_brick_props()
if split_screen: if split_screen:
bricks = props.split_screen_bricks bricks = props.split_screen_bricks
@@ -507,8 +487,7 @@ class BrickStore:
@classmethod @classmethod
def load_sub_roots(cls) -> None: def load_sub_roots(cls) -> None:
query = BrickStore.graph.query( query = BrickStore.graph.query("""
"""
PREFIX brick: <https://brickschema.org/schema/Brick#> PREFIX brick: <https://brickschema.org/schema/Brick#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?subRoot ?subClasses WHERE { SELECT ?subRoot ?subClasses WHERE {
@@ -525,8 +504,7 @@ class BrickStore:
} }
FILTER(?subClasses > 3) FILTER(?subClasses > 3)
} }
""" """)
)
for row in query: for row in query:
sub_root = row.get("subRoot").toPython().split("#")[-1] sub_root = row.get("subRoot").toPython().split("#")[-1]
BrickStore.root_classes.append(sub_root) BrickStore.root_classes.append(sub_root)
@@ -558,8 +536,7 @@ class BrickStore:
@classmethod @classmethod
def load_entity_classes(cls) -> None: def load_entity_classes(cls) -> None:
for root_class in BrickStore.root_classes: for root_class in BrickStore.root_classes:
query = BrickStore.graph.query( query = BrickStore.graph.query("""
"""
PREFIX brick: <https://brickschema.org/schema/Brick#> PREFIX brick: <https://brickschema.org/schema/Brick#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX owl: <http://www.w3.org/2002/07/owl#> PREFIX owl: <http://www.w3.org/2002/07/owl#>
@@ -569,25 +546,20 @@ class BrickStore:
?class owl:deprecated true . ?class owl:deprecated true .
} }
} }
""".replace( """.replace("{root_class}", root_class))
"{root_class}", root_class
)
)
BrickStore.entity_classes[root_class] = [] BrickStore.entity_classes[root_class] = []
for uri in sorted([x[0].toPython() for x in query]): for uri in sorted([x[0].toPython() for x in query]):
BrickStore.entity_classes[root_class].append(uri) BrickStore.entity_classes[root_class].append(uri)
@classmethod @classmethod
def load_relationships(cls) -> None: def load_relationships(cls) -> None:
query = BrickStore.graph.query( query = BrickStore.graph.query("""
"""
PREFIX brick: <https://brickschema.org/schema/Brick#> PREFIX brick: <https://brickschema.org/schema/Brick#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT DISTINCT ?relation WHERE { SELECT DISTINCT ?relation WHERE {
?relation rdfs:subPropertyOf brick:Relationship . ?relation rdfs:subPropertyOf brick:Relationship .
} }
""" """)
)
for uri in sorted([x[0].toPython() for x in query]): for uri in sorted([x[0].toPython() for x in query]):
BrickStore.relationships.append(uri) BrickStore.relationships.append(uri)
+2 -4
View File
@@ -2710,16 +2710,14 @@ class Drawing(bonsai.core.tool.Drawing):
return float(value) return float(value)
except: except:
pass # Perhaps it's imperial? pass # Perhaps it's imperial?
l = lark.Lark( l = lark.Lark("""start: feet? "-"? inches?
"""start: feet? "-"? inches?
feet: NUMBER? "-"? fraction? "'" feet: NUMBER? "-"? fraction? "'"
inches: NUMBER? "-"? fraction? "\\"" inches: NUMBER? "-"? fraction? "\\""
fraction: NUMBER "/" NUMBER fraction: NUMBER "/" NUMBER
%import common.NUMBER %import common.NUMBER
%import common.WS %import common.WS
%ignore WS // Disregard spaces in text %ignore WS // Disregard spaces in text
""" """)
)
try: try:
start = l.parse(value) start = l.parse(value)
@@ -22,8 +22,7 @@ class Generator:
} }
) )
query = self.schema.query( query = self.schema.query("""
"""
PREFIX brick: <https://brickschema.org/schema/Brick#> PREFIX brick: <https://brickschema.org/schema/Brick#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX skos: <http://www.w3.org/2004/02/skos/core#> PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
@@ -49,8 +48,7 @@ class Generator:
} }
} }
GROUP BY ?entity GROUP BY ?entity
""" """)
)
# create references dictionary # create references dictionary
references = {} references = {}
@@ -76,17 +74,13 @@ class Generator:
) )
# get all parents of the entity # get all parents of the entity
query = self.schema.query( query = self.schema.query("""
"""
PREFIX brick: <https://brickschema.org/schema/Brick#> PREFIX brick: <https://brickschema.org/schema/Brick#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?parent WHERE { SELECT ?parent WHERE {
brick:{entity} rdfs:subClassOf ?parent . brick:{entity} rdfs:subClassOf ?parent .
} }
""".replace( """.replace("{entity}", location.split("#")[-1]))
"{entity}", location.split("#")[-1]
)
)
# filter parents for the brick entity # filter parents for the brick entity
for row in query: for row in query:
parent = row.get("parent").toPython() parent = row.get("parent").toPython()
-1
View File
@@ -23,7 +23,6 @@ Use operators instead of `blender --command extension remove`
to ensure disable and enable occur in the same Blender session. to ensure disable and enable occur in the same Blender session.
""" """
import bpy import bpy
import bonsai.tool as tool import bonsai.tool as tool
+38 -76
View File
@@ -89,27 +89,22 @@ class COMMANDFILE:
f.write("# Linear Static Analysis With Self-Weight\n") f.write("# Linear Static Analysis With Self-Weight\n")
f.write( f.write("""
"""
# STEP: INITIALIZE STUDY # STEP: INITIALIZE STUDY
DEBUT( DEBUT(
PAR_LOT = 'NON' PAR_LOT = 'NON'
) )
""" """)
)
f.write( f.write("""
"""
# STEP: READ MED FILE # STEP: READ MED FILE
mesh = LIRE_MAILLAGE( mesh = LIRE_MAILLAGE(
FORMAT = 'MED', FORMAT = 'MED',
UNITE = 20 UNITE = 20
) )
""" """)
)
f.write( f.write("""
"""
# STEP: DEFINE MODEL # STEP: DEFINE MODEL
model = AFFE_MODELE( model = AFFE_MODELE(
MAILLAGE = mesh, MAILLAGE = mesh,
@@ -118,8 +113,7 @@ model = AFFE_MODELE(
TOUT = 'OUI', TOUT = 'OUI',
PHENOMENE = 'MECANIQUE', PHENOMENE = 'MECANIQUE',
MODELISATION = '3D' MODELISATION = '3D'
),""" ),""")
)
if faceGroupNames: if faceGroupNames:
template = """ template = """
@@ -157,12 +151,10 @@ model = AFFE_MODELE(
f.write(template.format(**context)) f.write(template.format(**context))
f.write( f.write("""
"""
) )
)\n )\n
""" """)
)
f.write("# STEP: DEFINE MATERIALS") f.write("# STEP: DEFINE MATERIALS")
@@ -195,12 +187,10 @@ model = AFFE_MODELE(
f.write(template.format(**context)) f.write(template.format(**context))
f.write( f.write("""
"""
material = AFFE_MATERIAU( material = AFFE_MATERIAU(
MAILLAGE = mesh, MAILLAGE = mesh,
AFFE = (""" AFFE = (""")
)
for i, material in enumerate(materials): for i, material in enumerate(materials):
template = """ template = """
@@ -227,20 +217,16 @@ material = AFFE_MATERIAU(
f.write(template.format(**context)) f.write(template.format(**context))
f.write( f.write("""
"""
) )
) )
""" """)
)
f.write( f.write("""
"""
# STEP: DEFINE ELEMENTS # STEP: DEFINE ELEMENTS
element = AFFE_CARA_ELEM( element = AFFE_CARA_ELEM(
MODELE = model, MODELE = model,
POUTRE = (""" POUTRE = (""")
)
for profile in profiles: for profile in profiles:
if profile["profileShape"] == "rectangular" and profile["profileType"] == "AREA": if profile["profileShape"] == "rectangular" and profile["profileType"] == "AREA":
@@ -296,11 +282,9 @@ element = AFFE_CARA_ELEM(
f.write(template.format(**context)) f.write(template.format(**context))
f.write( f.write("""
"""
), ),
COQUE = (""" COQUE = (""")
)
for el in [el for el in elements if el["geometryType"] == "surface"]: for el in [el for el in elements if el["geometryType"] == "surface"]:
@@ -319,15 +303,11 @@ element = AFFE_CARA_ELEM(
f.write(template.format(**context)) f.write(template.format(**context))
f.write( f.write("""
""" ),""")
),"""
)
f.write( f.write("""
""" ORIENTATION = (""")
ORIENTATION = ("""
)
for el in [el for el in elements if el["geometryType"] == "line"]: for el in [el for el in elements if el["geometryType"] == "line"]:
@@ -345,21 +325,16 @@ element = AFFE_CARA_ELEM(
f.write(template.format(**context)) f.write(template.format(**context))
f.write( f.write("""
""" ),""")
),"""
)
f.write( f.write("""
"""
)\n )\n
""" """)
)
f.write("# STEP: DEFINE SUPPORTS AND CONSTRAINTS") f.write("# STEP: DEFINE SUPPORTS AND CONSTRAINTS")
f.write( f.write("""
"""
liaisons = AFFE_CHAR_MECA( liaisons = AFFE_CHAR_MECA(
MODELE = model, MODELE = model,
DDL_IMPO = ( DDL_IMPO = (
@@ -372,14 +347,11 @@ liaisons = AFFE_CHAR_MECA(
DRY = 0.0, DRY = 0.0,
DRZ = 0.0 DRZ = 0.0
) )
),""" ),""")
)
if rigidLinkGroupNames: if rigidLinkGroupNames:
f.write( f.write("""
""" LIAISON_SOLIDE = (""")
LIAISON_SOLIDE = ("""
)
for groupName in rigidLinkGroupNames: for groupName in rigidLinkGroupNames:
template = """ template = """
@@ -391,16 +363,12 @@ liaisons = AFFE_CHAR_MECA(
f.write(template.format(**context)) f.write(template.format(**context))
f.write( f.write("""
""" ),""")
),"""
)
f.write( f.write("""
"""
) )
""" """)
)
template = """ template = """
# STEP: DEFINE LOAD # STEP: DEFINE LOAD
@@ -418,8 +386,7 @@ gravLoad = AFFE_CHAR_MECA(
f.write(template.format(**context)) f.write(template.format(**context))
f.write( f.write("""
"""
# STEP: RUN ANALYSIS # STEP: RUN ANALYSIS
res_Bld = MECA_STATIQUE( res_Bld = MECA_STATIQUE(
MODELE = model, MODELE = model,
@@ -434,8 +401,7 @@ res_Bld = MECA_STATIQUE(
) )
) )
) )
""" """)
)
# f.write( # f.write(
# ''' # '''
@@ -515,8 +481,7 @@ res_Bld = MECA_STATIQUE(
# ''' # '''
# ) # )
# #
f.write( f.write("""
"""
# STEP: DEFORMED SHAPE EXTRACTION # STEP: DEFORMED SHAPE EXTRACTION
IMPR_RESU( IMPR_RESU(
FORMAT = 'MED', FORMAT = 'MED',
@@ -527,15 +492,12 @@ IMPR_RESU(
NOM_CHAM_MED = ('Bld_DISP',), # 'Bld_REAC', 'Bld_FORC' NOM_CHAM_MED = ('Bld_DISP',), # 'Bld_REAC', 'Bld_FORC'
) )
) )
""" """)
)
f.write( f.write("""
"""
# STEP: CONCLUDE STUDY # STEP: CONCLUDE STUDY
FIN() FIN()
""" """)
)
f.close() f.close()
+3 -3
View File
@@ -53,16 +53,16 @@ class MODEL:
"""Function to define a Point from """Function to define a Point from
a polyline (list of 1 point)""" a polyline (list of 1 point)"""
(x, y, z) = pl x, y, z = pl
return self.geompy.MakeVertex(x, y, z) return self.geompy.MakeVertex(x, y, z)
def makeLine(self, pl): def makeLine(self, pl):
"""Function to define a Line from """Function to define a Line from
a polyline (list of 2 points)""" a polyline (list of 2 points)"""
(x, y, z) = pl[0] x, y, z = pl[0]
P1 = self.geompy.MakeVertex(x, y, z) P1 = self.geompy.MakeVertex(x, y, z)
(x, y, z) = pl[1] x, y, z = pl[1]
P2 = self.geompy.MakeVertex(x, y, z) P2 = self.geompy.MakeVertex(x, y, z)
return self.geompy.MakeLineTwoPnt(P1, P2) return self.geompy.MakeLineTwoPnt(P1, P2)
@@ -28,12 +28,8 @@ use_step_matcher("parse")
@step('There must be exactly {number} "{ifc_class}" elements') @step('There must be exactly {number} "{ifc_class}" elements')
def step_impl(context, number, ifc_class): def step_impl(context, number, ifc_class):
num = len(IfcStore.file.by_type(ifc_class)) num = len(IfcStore.file.by_type(ifc_class))
assert num == int( assert num == int(number), "Could not find {} elements of {}. \
number Found {} element(s).".format(number, ifc_class, num)
), "Could not find {} elements of {}. \
Found {} element(s).".format(
number, ifc_class, num
)
@given('a set of (key,value) called ("{key_name}","{value_name}")') @given('a set of (key,value) called ("{key_name}","{value_name}")')
@@ -95,13 +91,9 @@ def step_impl(context, attribute_name):
@then('there must be exactly a number of "{ifc_class}" equals to the number of distinct value') @then('there must be exactly a number of "{ifc_class}" equals to the number of distinct value')
def step_impl(context, ifc_class): def step_impl(context, ifc_class):
try: try:
context.execute_steps( context.execute_steps("""
"""
then There must be exactly {number} "{ifc_class}" elements then There must be exactly {number} "{ifc_class}" elements
""".format( """.format(ifc_class=ifc_class, number=context.model.get_count_distinct_values()))
ifc_class=ifc_class, number=context.model.get_count_distinct_values()
)
)
except AssertionError as error: except AssertionError as error:
str_error = str(error) str_error = str(error)
assert False, str_error[: str_error.find("Traceback")] assert False, str_error[: str_error.find("Traceback")]
@@ -51,13 +51,9 @@ def step_impl(context, path_file):
@then("there must be exactly a number of {ifc_class} equals to the number of distinct row value") @then("there must be exactly a number of {ifc_class} equals to the number of distinct row value")
def step_impl(context, ifc_class): def step_impl(context, ifc_class):
try: try:
context.execute_steps( context.execute_steps("""
"""
then There must be exactly {number} {ifc_class} elements then There must be exactly {number} {ifc_class} elements
""".format( """.format(ifc_class=ifc_class, number=context.model.get_count_distinct_values()))
ifc_class=ifc_class, number=context.model.get_count_distinct_values()
)
)
except AssertionError as error: except AssertionError as error:
str_error = str(error) str_error = str(error)
assert False, str_error[: str_error.find("Traceback")] assert False, str_error[: str_error.find("Traceback")]
@@ -53,6 +53,7 @@ Example:
for wall in walls: for wall in walls:
print(wall.Name) print(wall.Name)
""" """
from __future__ import annotations from __future__ import annotations
import os import os
@@ -217,8 +217,7 @@ for id in to_emit:
statements.append("%s << %s" % (id, stmt)) statements.append("%s << %s" % (id, stmt))
if __name__ == "__main__": if __name__ == "__main__":
print( print(r"""
r"""
# This file is generated by IfcOpenShell ifcexpressparser bootstrap.py # This file is generated by IfcOpenShell ifcexpressparser bootstrap.py
from __future__ import annotations from __future__ import annotations
@@ -257,6 +256,4 @@ if __name__ == "__main__":
mdl = importlib.import_module(output) mdl = importlib.import_module(output)
mdl.Generator(m).emit() mdl.Generator(m).emit()
sys.stdout.write(m.schema.name) sys.stdout.write(m.schema.name)
""" """ % ("\n ".join(statements)))
% ("\n ".join(statements))
)
@@ -363,24 +363,18 @@ class EarlyBoundCodeWriter:
) )
) )
self.statements[self.statements.index("{factory_placeholder}")] = ( self.statements[self.statements.index("{factory_placeholder}")] = """
"""
class %(schema_name)s_instance_factory : public IfcParse::instance_factory { class %(schema_name)s_instance_factory : public IfcParse::instance_factory {
virtual IfcUtil::IfcBaseClass* operator()(const IfcParse::declaration* decl, IfcEntityInstanceData&& data) const { virtual IfcUtil::IfcBaseClass* operator()(const IfcParse::declaration* decl, IfcEntityInstanceData&& data) const {
%(instance_mapping)s %(instance_mapping)s
} }
}; };
""" """ % locals()
% locals()
)
"" ""
self.statements[self.statements.index("{string_pool_placeholder}")] = ( self.statements[self.statements.index("{string_pool_placeholder}")] = """
"""
const std::string strings[] = {%s}; const std::string strings[] = {%s};
""" """ % ",".join(map(lambda s: '"%s"s' % s, self.strings))
% ",".join(map(lambda s: '"%s"s' % s, self.strings))
)
def __str__(self): def __str__(self):
return "\n".join(self.statements) return "\n".join(self.statements)
@@ -145,8 +145,7 @@ class configuration:
config.set( config.set(
"snippets", "snippets",
"print all wall ids", "print all wall ids",
self.config_encode( self.config_encode("""
"""
########################################################################### ###########################################################################
# A simple script that iterates over all walls in the current model # # A simple script that iterates over all walls in the current model #
# and prints their Globally unique IDs (GUIDS) to the console window # # and prints their Globally unique IDs (GUIDS) to the console window #
@@ -154,15 +153,13 @@ class configuration:
for wall in model.by_type("IfcWall"): for wall in model.by_type("IfcWall"):
print ("wall with global id: "+str(wall.GlobalId)) print ("wall with global id: "+str(wall.GlobalId))
""".lstrip() """.lstrip()),
),
) )
config.set( config.set(
"snippets", "snippets",
"print properties of current selection", "print properties of current selection",
self.config_encode( self.config_encode("""
"""
########################################################################### ###########################################################################
# A simple script that iterates over all IfcPropertySets of the currently # # A simple script that iterates over all IfcPropertySets of the currently #
# selected object and prints them to the console # # selected object and prints them to the console #
@@ -180,8 +177,7 @@ if selection:
for prop in relDefinesByProperties.RelatingPropertyDefinition.HasProperties: for prop in relDefinesByProperties.RelatingPropertyDefinition.HasProperties:
print ("{:<20} :{}".format(prop.Name,prop.NominalValue.wrappedValue)) print ("{:<20} :{}".format(prop.Name,prop.NominalValue.wrappedValue))
print ("\\n") print ("\\n")
""".lstrip() """.lstrip()),
),
) )
with open(conf_file, "w") as configfile: with open(conf_file, "w") as configfile:
config.write(configfile) config.write(configfile)
@@ -352,8 +352,7 @@ def get_cost_rate(
class CostValueUnserialiser: class CostValueUnserialiser:
def parse(self, formula: str): def parse(self, formula: str):
l = lark.Lark( l = lark.Lark("""start: formula
"""start: formula
formula: operand (operator operand)* formula: operand (operator operand)*
operand: value | category "(" formula ")" operand: value | category "(" formula ")"
value: NUMBER? value: NUMBER?
@@ -390,8 +389,7 @@ class CostValueUnserialiser:
NEWLINE: (CR? LF)+ NEWLINE: (CR? LF)+
%ignore WS // Disregard spaces in text %ignore WS // Disregard spaces in text
""" """)
)
start = l.parse(formula) start = l.parse(formula)
return self.get_formula(start.children[0]) return self.get_formula(start.children[0])
@@ -25,7 +25,6 @@ Things we do check:
- class hierarchy - class hierarchy
""" """
import ast import ast
import difflib import difflib
from pathlib import Path from pathlib import Path
@@ -39,8 +39,7 @@ import ifcopenshell.util.shape
import ifcopenshell.util.system import ifcopenshell.util.system
import ifcopenshell.util.unit import ifcopenshell.util.unit
filter_elements_grammar = lark.Lark( filter_elements_grammar = lark.Lark("""start: filter_group
"""start: filter_group
filter_group: facet_list ("+" facet_list)* filter_group: facet_list ("+" facet_list)*
facet_list: facet ("," facet)* facet_list: facet ("," facet)*
@@ -111,11 +110,9 @@ filter_elements_grammar = lark.Lark(
NEWLINE: (CR? LF)+ NEWLINE: (CR? LF)+
%ignore WS // Disregard spaces in text %ignore WS // Disregard spaces in text
""" """)
)
get_element_grammar = lark.Lark( get_element_grammar = lark.Lark("""start: keys
"""start: keys
keys: key ("." key)* keys: key ("." key)*
key: quoted_string | regex_string | unquoted_string key: quoted_string | regex_string | unquoted_string
@@ -130,11 +127,9 @@ get_element_grammar = lark.Lark(
WS: /[ \\t\\f\\r\\n]/+ WS: /[ \\t\\f\\r\\n]/+
%ignore WS // Disregard spaces in text %ignore WS // Disregard spaces in text
""" """)
)
format_grammar = lark.Lark( format_grammar = lark.Lark("""start: expression
"""start: expression
?expression: add_sub ?expression: add_sub
?add_sub: mul_div ?add_sub: mul_div
@@ -193,8 +188,7 @@ format_grammar = lark.Lark(
NEWLINE: (CR? LF)+ NEWLINE: (CR? LF)+
%ignore WS // Disregard spaces in text %ignore WS // Disregard spaces in text
""" """)
)
class FormatTransformer(lark.Transformer): class FormatTransformer(lark.Transformer):
@@ -21,7 +21,6 @@ This file should produce no warnings from type checker (currently pyright).
Those tests are not automatically checked and just there to make sure overloads are making sense. Those tests are not automatically checked and just there to make sure overloads are making sense.
""" """
from typing import Union from typing import Union
from typing_extensions import assert_type from typing_extensions import assert_type
@@ -17,6 +17,7 @@
# along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>. # along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>.
"""Run this test from src/ifcopenshell-python folder: pytest --durations=0 ifcopenshell/util/test_pset.py""" """Run this test from src/ifcopenshell-python folder: pytest --durations=0 ifcopenshell/util/test_pset.py"""
from ifcopenshell.util import pset from ifcopenshell.util import pset
from ifcopenshell.util.pset import ApplicableEntity from ifcopenshell.util.pset import ApplicableEntity
@@ -55,8 +55,7 @@ class Patcher:
self.c = self.db.cursor() self.c = self.db.cursor()
self.file_patched = db_file self.file_patched = db_file
self.c.execute( self.c.execute("""
"""
CREATE TABLE IF NOT EXISTS elements ( CREATE TABLE IF NOT EXISTS elements (
id integer PRIMARY KEY NOT NULL UNIQUE, id integer PRIMARY KEY NOT NULL UNIQUE,
global_id text, global_id text,
@@ -65,33 +64,28 @@ class Patcher:
name text, name text,
description text description text
); );
""" """)
)
self.c.execute("CREATE INDEX IF NOT EXISTS idx_global_id ON elements (global_id);") self.c.execute("CREATE INDEX IF NOT EXISTS idx_global_id ON elements (global_id);")
self.c.execute("CREATE INDEX IF NOT EXISTS idx_ifc_class ON elements (ifc_class);") self.c.execute("CREATE INDEX IF NOT EXISTS idx_ifc_class ON elements (ifc_class);")
self.c.execute("CREATE INDEX IF NOT EXISTS idx_predefined_type ON elements (predefined_type);") self.c.execute("CREATE INDEX IF NOT EXISTS idx_predefined_type ON elements (predefined_type);")
self.c.execute( self.c.execute("""
"""
CREATE TABLE IF NOT EXISTS relationships ( CREATE TABLE IF NOT EXISTS relationships (
from_id integer NOT NULL, from_id integer NOT NULL,
type text, type text,
to_id integer NOT NULL to_id integer NOT NULL
); );
""" """)
)
self.c.execute("CREATE INDEX IF NOT EXISTS idx_from_id ON relationships (from_id);") self.c.execute("CREATE INDEX IF NOT EXISTS idx_from_id ON relationships (from_id);")
self.c.execute( self.c.execute("""
"""
CREATE TABLE IF NOT EXISTS properties ( CREATE TABLE IF NOT EXISTS properties (
element_id integer NOT NULL, element_id integer NOT NULL,
set_name text, set_name text,
name text, name text,
value text value text
); );
""" """)
)
self.c.execute("CREATE INDEX IF NOT EXISTS idx_element_id ON properties (element_id);") self.c.execute("CREATE INDEX IF NOT EXISTS idx_element_id ON properties (element_id);")
elements = self.file.by_type("IfcObjectDefinition") elements = self.file.by_type("IfcObjectDefinition")
+2 -4
View File
@@ -349,13 +349,11 @@ class Patcher(ifcpatch.BasePatcher):
assert cursor is not None assert cursor is not None
row = cursor.fetchone() row = cursor.fetchone()
elif self.sql_type == "mysql": elif self.sql_type == "mysql":
cursor = self.c.execute( cursor = self.c.execute(f"""
f"""
SELECT 1 FROM information_schema.tables SELECT 1 FROM information_schema.tables
WHERE table_schema = '{self.database}' AND table_name = 'id_map' WHERE table_schema = '{self.database}' AND table_name = 'id_map'
LIMIT 1; LIMIT 1;
""" """)
)
row = self.c.fetchone() row = self.c.fetchone()
else: else:
assert_never(self.sql_type) assert_never(self.sql_type)
+4 -10
View File
@@ -694,8 +694,7 @@ class BCFDB(MyDB):
snapshot_type = "" snapshot_type = ""
snapshot = False snapshot = False
set_snapshot = "" set_snapshot = ""
cypher_viewpoint = ( cypher_viewpoint = """
"""
MATCH (u:User)-[r1:HAS_ACTIONS_ON]->(p:Project)-[r2:HAS]->(t:Topic) MATCH (u:User)-[r1:HAS_ACTIONS_ON]->(p:Project)-[r2:HAS]->(t:Topic)
WHERE u.username = $username WHERE u.username = $username
AND r1.createViewpoint = True AND r1.createViewpoint = True
@@ -713,9 +712,7 @@ class BCFDB(MyDB):
v.spaces_visible = $spaces_visible, v.spaces_visible = $spaces_visible,
v.space_boundaries_visible = $space_boundaries_visible, v.space_boundaries_visible = $space_boundaries_visible,
v.openings_visible = $openings_visible v.openings_visible = $openings_visible
""" """ % set_snapshot
% set_snapshot
)
if viewpoint.guid is None: if viewpoint.guid is None:
viewpoint.guid = uuid4() viewpoint.guid = uuid4()
if viewpoint.orthogonal_camera is None: if viewpoint.orthogonal_camera is None:
@@ -1450,8 +1447,7 @@ class BCFDB(MyDB):
else: else:
document_url = "" document_url = ""
document_reference.url = "" document_reference.url = ""
cypher = ( cypher = """
"""
MATCH (u:User)-[r1:HAS_ACTIONS_ON]->(p:Project)-[r2:HAS]->(t:Topic) MATCH (u:User)-[r1:HAS_ACTIONS_ON]->(p:Project)-[r2:HAS]->(t:Topic)
WHERE u.username = $username WHERE u.username = $username
AND r1.updateDocumentReferences = True AND r1.updateDocumentReferences = True
@@ -1461,9 +1457,7 @@ class BCFDB(MyDB):
SET r3.guid: $document_reference_id, SET r3.guid: $document_reference_id,
%s %s
d.description = $description d.description = $description
""" """ % document_url
% document_url
)
result = tx.run( result = tx.run(
cypher, cypher,
username=current_user.username, username=current_user.username,
@@ -36,17 +36,14 @@ class DOCDB(MyDB):
else: else:
version_index_criteria = "AND d.version_index = $version_index" version_index_criteria = "AND d.version_index = $version_index"
cypher = ( cypher = """
"""
MATCH (d:Document) MATCH (d:Document)
WHERE d.document_id = $document_id WHERE d.document_id = $document_id
%s %s
RETURN d AS document RETURN d AS document
ORDER by d.version_index DESC ORDER by d.version_index DESC
LIMIT 1 LIMIT 1
""" """ % version_index_criteria
% version_index_criteria
)
result = tx.run(cypher, document_id=document_id, version_index=version_index) result = tx.run(cypher, document_id=document_id, version_index=version_index)
@@ -891,8 +888,7 @@ class DOCDB(MyDB):
else: else:
version_index_criteria = "" version_index_criteria = ""
cypher = ( cypher = """
"""
MATCH (u:User)-[r3:HAS_ACTIONS_ON]->(p:Project)-[r4:CONTAINS]->(d:Document) MATCH (u:User)-[r3:HAS_ACTIONS_ON]->(p:Project)-[r4:CONTAINS]->(d:Document)
WHERE u.username = $username WHERE u.username = $username
AND d.document_id = $document_id AND d.document_id = $document_id
@@ -900,9 +896,7 @@ class DOCDB(MyDB):
RETURN d AS document RETURN d AS document
ORDER by d.version_index DESC ORDER by d.version_index DESC
LIMIT 1 LIMIT 1
""" """ % version_index_criteria
% version_index_criteria
)
result = tx.run( result = tx.run(
cypher, username=current_user.username, document_id=document_id, version_index=version_index cypher, username=current_user.username, document_id=document_id, version_index=version_index
@@ -927,8 +921,7 @@ class DOCDB(MyDB):
else: else:
version_index_criteria = "" version_index_criteria = ""
cypher = ( cypher = """
"""
MATCH (u:User)-[r3:HAS_ACTIONS_ON]->(p:Project)-[r4:CONTAINS]->(d:Document) MATCH (u:User)-[r3:HAS_ACTIONS_ON]->(p:Project)-[r4:CONTAINS]->(d:Document)
WHERE u.username = $username WHERE u.username = $username
AND d.document_id = $document_id AND d.document_id = $document_id
@@ -936,9 +929,7 @@ class DOCDB(MyDB):
RETURN d AS document RETURN d AS document
ORDER by d.version_index DESC ORDER by d.version_index DESC
LIMIT 1 LIMIT 1
""" """ % version_index_criteria
% version_index_criteria
)
result = tx.run( result = tx.run(
cypher, username=current_user.username, document_id=document_id, version_index=version_index cypher, username=current_user.username, document_id=document_id, version_index=version_index