bimora-open-source 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bimora/__init__.py +72 -0
- bimora/api.py +99 -0
- bimora/cli.py +474 -0
- bimora/errors.py +31 -0
- bimora/ifc/__init__.py +1 -0
- bimora/ifc/extract.py +377 -0
- bimora/ifc/loader.py +146 -0
- bimora/ifc/model.py +124 -0
- bimora/ifc/units.py +127 -0
- bimora/interoperability/__init__.py +1 -0
- bimora/interoperability/bcf.py +189 -0
- bimora/interoperability/compare.py +204 -0
- bimora/interoperability/csv_export.py +157 -0
- bimora/interoperability/identifiers.py +63 -0
- bimora/interoperability/json_export.py +65 -0
- bimora/interoperability/manifest.py +100 -0
- bimora/interoperability/mapping.py +152 -0
- bimora/py.typed +0 -0
- bimora/reporting/__init__.py +1 -0
- bimora/reporting/report.py +97 -0
- bimora/schemas/__init__.py +1 -0
- bimora/schemas/asset-manifest.schema.json +29 -0
- bimora/schemas/model.schema.json +97 -0
- bimora/spatial/__init__.py +1 -0
- bimora/spatial/analysis.py +192 -0
- bimora/spatial/units.py +109 -0
- bimora/validation/__init__.py +1 -0
- bimora/validation/config.py +114 -0
- bimora/validation/engine.py +398 -0
- bimora_open_source-0.1.0.dist-info/METADATA +179 -0
- bimora_open_source-0.1.0.dist-info/RECORD +34 -0
- bimora_open_source-0.1.0.dist-info/WHEEL +4 -0
- bimora_open_source-0.1.0.dist-info/entry_points.txt +2 -0
- bimora_open_source-0.1.0.dist-info/licenses/LICENSE +21 -0
bimora/__init__.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""BIMORA Open Source — IFC metadata extraction, architectural data validation, spatial summaries and revision
|
|
2
|
+
comparison.
|
|
3
|
+
|
|
4
|
+
Quick start::
|
|
5
|
+
|
|
6
|
+
from bimora import inspect_model, validate_model
|
|
7
|
+
|
|
8
|
+
summary = inspect_model("model.ifc")
|
|
9
|
+
results = validate_model("model.ifc")
|
|
10
|
+
for finding in results.findings:
|
|
11
|
+
print(finding.rule_id, finding.severity, finding.description)
|
|
12
|
+
|
|
13
|
+
Validation results are data-quality checks. They are not building-code compliance checking, engineering approval
|
|
14
|
+
or professional design verification.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
__version__ = "0.1.0"
|
|
20
|
+
|
|
21
|
+
from bimora.api import (
|
|
22
|
+
build_report,
|
|
23
|
+
compare_models,
|
|
24
|
+
export_model,
|
|
25
|
+
extract_properties,
|
|
26
|
+
extract_spaces,
|
|
27
|
+
inspect_model,
|
|
28
|
+
validate_model,
|
|
29
|
+
)
|
|
30
|
+
from bimora.errors import (
|
|
31
|
+
BimoraError,
|
|
32
|
+
ConfigError,
|
|
33
|
+
FileTooLargeError,
|
|
34
|
+
InputError,
|
|
35
|
+
ParseError,
|
|
36
|
+
UnsupportedFormatError,
|
|
37
|
+
UnsupportedSchemaError,
|
|
38
|
+
)
|
|
39
|
+
from bimora.ifc.extract import read_model
|
|
40
|
+
from bimora.ifc.loader import VERIFIED_SCHEMAS, load_model, sniff_schema
|
|
41
|
+
from bimora.ifc.model import Element, ModelData, Quantity, SpatialNode
|
|
42
|
+
from bimora.spatial.units import convert
|
|
43
|
+
from bimora.validation.engine import Finding, ValidationResult
|
|
44
|
+
|
|
45
|
+
__all__ = [
|
|
46
|
+
"VERIFIED_SCHEMAS",
|
|
47
|
+
"BimoraError",
|
|
48
|
+
"ConfigError",
|
|
49
|
+
"Element",
|
|
50
|
+
"FileTooLargeError",
|
|
51
|
+
"Finding",
|
|
52
|
+
"InputError",
|
|
53
|
+
"ModelData",
|
|
54
|
+
"ParseError",
|
|
55
|
+
"Quantity",
|
|
56
|
+
"SpatialNode",
|
|
57
|
+
"UnsupportedFormatError",
|
|
58
|
+
"UnsupportedSchemaError",
|
|
59
|
+
"ValidationResult",
|
|
60
|
+
"__version__",
|
|
61
|
+
"build_report",
|
|
62
|
+
"compare_models",
|
|
63
|
+
"convert",
|
|
64
|
+
"export_model",
|
|
65
|
+
"extract_properties",
|
|
66
|
+
"extract_spaces",
|
|
67
|
+
"inspect_model",
|
|
68
|
+
"load_model",
|
|
69
|
+
"read_model",
|
|
70
|
+
"sniff_schema",
|
|
71
|
+
"validate_model",
|
|
72
|
+
]
|
bimora/api.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Public Python API.
|
|
2
|
+
|
|
3
|
+
Every function accepts either a path to an ``.ifc`` file or a :class:`~bimora.ifc.model.ModelData` that was
|
|
4
|
+
already extracted with :func:`read_model` (to avoid parsing the same file twice).
|
|
5
|
+
|
|
6
|
+
>>> from bimora import inspect_model, validate_model
|
|
7
|
+
>>> summary = inspect_model("examples/pavilion-ifc4.ifc") # doctest: +SKIP
|
|
8
|
+
>>> results = validate_model("examples/pavilion-ifc4.ifc") # doctest: +SKIP
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any, Literal
|
|
16
|
+
|
|
17
|
+
from bimora.ifc.extract import read_model
|
|
18
|
+
from bimora.ifc.loader import DEFAULT_MAX_BYTES
|
|
19
|
+
from bimora.ifc.model import ModelData
|
|
20
|
+
from bimora.interoperability import csv_export, json_export
|
|
21
|
+
from bimora.interoperability.compare import ComparisonResult
|
|
22
|
+
from bimora.interoperability.compare import compare_models as _compare
|
|
23
|
+
from bimora.reporting import report as _report
|
|
24
|
+
from bimora.spatial import analysis
|
|
25
|
+
from bimora.validation.engine import ValidationResult, validate
|
|
26
|
+
|
|
27
|
+
ModelSource = str | os.PathLike[str] | ModelData
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _model(
|
|
31
|
+
source: ModelSource, *, max_bytes: int = DEFAULT_MAX_BYTES, allow_untested_schema: bool = False
|
|
32
|
+
) -> ModelData:
|
|
33
|
+
if isinstance(source, ModelData):
|
|
34
|
+
return source
|
|
35
|
+
return read_model(Path(source), max_bytes=max_bytes, allow_untested_schema=allow_untested_schema)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def inspect_model(source: ModelSource, **load: Any) -> dict[str, Any]:
|
|
39
|
+
"""Schema, project, units, hierarchy counts, storeys, property / quantity sets, materials and classifications."""
|
|
40
|
+
return _report.inspection_summary(_model(source, **load))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def validate_model(
|
|
44
|
+
source: ModelSource, config: dict[str, Any] | str | Path | None = None, **load: Any
|
|
45
|
+
) -> ValidationResult:
|
|
46
|
+
"""Run the architectural data validation rules (see :mod:`bimora.validation.engine`).
|
|
47
|
+
|
|
48
|
+
``config`` is a merged configuration dict, a path to a JSON / TOML configuration file, or ``None``.
|
|
49
|
+
The result is a data-quality check, not code compliance or professional verification.
|
|
50
|
+
"""
|
|
51
|
+
return validate(_model(source, **load), config)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def extract_spaces(source: ModelSource, **load: Any) -> list[dict[str, Any]]:
|
|
55
|
+
"""Room inventory: number, name, storey, category and declared floor areas of every space."""
|
|
56
|
+
return analysis.room_inventory(_model(source, **load))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def extract_properties(source: ModelSource, include_spaces: bool = True, **load: Any) -> list[dict[str, Any]]:
|
|
60
|
+
"""One row per property value: GlobalId, class, name, storey, property set, property, value."""
|
|
61
|
+
return csv_export.property_rows(_model(source, **load), include_spaces=include_spaces)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def export_model(
|
|
65
|
+
source: ModelSource,
|
|
66
|
+
format: Literal["json", "csv"] = "json",
|
|
67
|
+
output: str | Path | None = None,
|
|
68
|
+
**load: Any,
|
|
69
|
+
) -> dict[str, Any] | dict[str, Path]:
|
|
70
|
+
"""Export to JSON (returns the document; writes it when ``output`` is a file path) or CSV (writes files into
|
|
71
|
+
the ``output`` directory, default: current directory, and returns their paths)."""
|
|
72
|
+
model = _model(source, **load)
|
|
73
|
+
if format == "json":
|
|
74
|
+
doc = json_export.model_to_json(model)
|
|
75
|
+
if output is not None:
|
|
76
|
+
json_export.write_json(doc, output)
|
|
77
|
+
return doc
|
|
78
|
+
if format == "csv":
|
|
79
|
+
return csv_export.export_csv(model, output or ".")
|
|
80
|
+
raise ValueError("format must be 'json' or 'csv'")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def compare_models(before: ModelSource, after: ModelSource, **load: Any) -> ComparisonResult:
|
|
84
|
+
"""Metadata comparison of two revisions matched by GlobalId (not geometry, not clash detection)."""
|
|
85
|
+
return _compare(_model(before, **load), _model(after, **load))
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def build_report(
|
|
89
|
+
source: ModelSource,
|
|
90
|
+
config: dict[str, Any] | str | Path | None = None,
|
|
91
|
+
area_unit: str = "m2",
|
|
92
|
+
min_severity: str = "info",
|
|
93
|
+
**load: Any,
|
|
94
|
+
) -> dict[str, Any]:
|
|
95
|
+
"""Inspection, spatial summaries and validation in one reproducible document."""
|
|
96
|
+
model = _model(source, **load)
|
|
97
|
+
return _report.build_report(
|
|
98
|
+
model, validate(model, config), area_unit=area_unit, min_severity=min_severity
|
|
99
|
+
)
|
bimora/cli.py
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
"""Command-line interface: ``bimora <command> …`` (run ``bimora --help``).
|
|
2
|
+
|
|
3
|
+
Exit codes: 0 success · 1 check failed (validation findings at or above ``--fail-on``, changes with
|
|
4
|
+
``--fail-on-changes``, manifest problems) · 2 usage error · 3 input or configuration error · 4 output error.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import json
|
|
11
|
+
import sys
|
|
12
|
+
from collections.abc import Sequence
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from bimora import __version__
|
|
17
|
+
from bimora.errors import BimoraError
|
|
18
|
+
from bimora.ifc.loader import DEFAULT_MAX_BYTES, VERIFIED_SCHEMAS
|
|
19
|
+
|
|
20
|
+
EXIT_OK, EXIT_CHECK_FAILED, EXIT_USAGE, EXIT_INPUT, EXIT_OUTPUT = 0, 1, 2, 3, 4
|
|
21
|
+
SEVERITIES = ("info", "warning", "error")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class _OutputError(Exception):
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
29
|
+
"""Entry point of the ``bimora`` command."""
|
|
30
|
+
for stream in (sys.stdout, sys.stderr):
|
|
31
|
+
reconfigure = getattr(stream, "reconfigure", None)
|
|
32
|
+
if reconfigure is not None:
|
|
33
|
+
reconfigure(errors="backslashreplace")
|
|
34
|
+
parser = build_parser()
|
|
35
|
+
args = parser.parse_args(argv)
|
|
36
|
+
if not getattr(args, "handler", None):
|
|
37
|
+
parser.print_help()
|
|
38
|
+
return EXIT_USAGE
|
|
39
|
+
try:
|
|
40
|
+
code: int = args.handler(args)
|
|
41
|
+
return code
|
|
42
|
+
except BimoraError as exc:
|
|
43
|
+
print(f"bimora: error: {exc}", file=sys.stderr)
|
|
44
|
+
return EXIT_INPUT
|
|
45
|
+
except _OutputError as exc:
|
|
46
|
+
print(f"bimora: error: {exc}", file=sys.stderr)
|
|
47
|
+
return EXIT_OUTPUT
|
|
48
|
+
except ValueError as exc:
|
|
49
|
+
print(f"bimora: error: {exc}", file=sys.stderr)
|
|
50
|
+
return EXIT_USAGE
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# ── parser ───────────────────────────────────────────────────────────────────
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
57
|
+
p = argparse.ArgumentParser(
|
|
58
|
+
prog="bimora",
|
|
59
|
+
description="BIMORA Open Source: inspect, validate, summarise, export and compare IFC models. "
|
|
60
|
+
f"Verified schemas: {', '.join(sorted(VERIFIED_SCHEMAS))}. Validation is a data-quality check, not code "
|
|
61
|
+
"compliance or professional verification.",
|
|
62
|
+
epilog="Exit codes: 0 ok, 1 check failed, 2 usage error, 3 input/config error, 4 output error.",
|
|
63
|
+
)
|
|
64
|
+
p.add_argument("--version", action="version", version=f"bimora-open-source {__version__}")
|
|
65
|
+
sub = p.add_subparsers(title="commands", metavar="<command>")
|
|
66
|
+
|
|
67
|
+
def model_cmd(name: str, help_text: str) -> argparse.ArgumentParser:
|
|
68
|
+
c = sub.add_parser(name, help=help_text, description=help_text)
|
|
69
|
+
c.add_argument("file", type=Path, help="IFC file (.ifc, STEP encoding)")
|
|
70
|
+
_load_options(c)
|
|
71
|
+
return c
|
|
72
|
+
|
|
73
|
+
c = model_cmd("inspect", "Summarise schema, project, units, hierarchy and element counts.")
|
|
74
|
+
_output_options(c)
|
|
75
|
+
c.set_defaults(handler=cmd_inspect)
|
|
76
|
+
|
|
77
|
+
c = model_cmd("validate", "Run the architectural data validation rules.")
|
|
78
|
+
c.add_argument("--config", type=Path, help="validation configuration (.json or .toml)")
|
|
79
|
+
c.add_argument(
|
|
80
|
+
"--min-severity", choices=SEVERITIES, default="info", help="hide findings below this severity"
|
|
81
|
+
)
|
|
82
|
+
c.add_argument(
|
|
83
|
+
"--fail-on",
|
|
84
|
+
choices=(*SEVERITIES, "never"),
|
|
85
|
+
default="error",
|
|
86
|
+
help="exit with 1 when findings of this severity or worse exist (default: error)",
|
|
87
|
+
)
|
|
88
|
+
_output_options(c)
|
|
89
|
+
c.set_defaults(handler=cmd_validate)
|
|
90
|
+
|
|
91
|
+
c = model_cmd("spaces", "Room inventory with declared floor areas, plus area totals per storey.")
|
|
92
|
+
c.add_argument("--area-unit", choices=("m2", "ft2"), default="m2", help="unit of the area totals")
|
|
93
|
+
c.add_argument("--csv", action="store_true", help="write the room inventory as CSV")
|
|
94
|
+
_output_options(c)
|
|
95
|
+
c.set_defaults(handler=cmd_spaces)
|
|
96
|
+
|
|
97
|
+
c = model_cmd("properties", "List property values (one row per element / property).")
|
|
98
|
+
c.add_argument("--ifc-class", help="only this IFC class (for example IfcWall)")
|
|
99
|
+
c.add_argument("--pset", help="only this property set")
|
|
100
|
+
c.add_argument("--csv", action="store_true", help="write CSV instead of JSON / text")
|
|
101
|
+
_output_options(c)
|
|
102
|
+
c.set_defaults(handler=cmd_properties)
|
|
103
|
+
|
|
104
|
+
c = model_cmd("export", "Export metadata to JSON or CSV.")
|
|
105
|
+
c.add_argument("--format", choices=("json", "csv"), required=True)
|
|
106
|
+
c.add_argument(
|
|
107
|
+
"--output",
|
|
108
|
+
"-o",
|
|
109
|
+
type=Path,
|
|
110
|
+
help="JSON: output file (default: stdout). CSV: output directory (default: current directory)",
|
|
111
|
+
)
|
|
112
|
+
c.add_argument(
|
|
113
|
+
"--mapping", type=Path, help="CSV field mapping (JSON): writes one mapped CSV file to --output"
|
|
114
|
+
)
|
|
115
|
+
c.set_defaults(handler=cmd_export)
|
|
116
|
+
|
|
117
|
+
c = sub.add_parser(
|
|
118
|
+
"compare", help="Compare two revisions by GlobalId (metadata only, not clash detection)."
|
|
119
|
+
)
|
|
120
|
+
c.add_argument("before", type=Path)
|
|
121
|
+
c.add_argument("after", type=Path)
|
|
122
|
+
c.add_argument("--fail-on-changes", action="store_true", help="exit with 1 when any difference is found")
|
|
123
|
+
_load_options(c)
|
|
124
|
+
_output_options(c)
|
|
125
|
+
c.set_defaults(handler=cmd_compare)
|
|
126
|
+
|
|
127
|
+
c = model_cmd("report", "Inspection, spatial summaries and validation in one JSON report.")
|
|
128
|
+
c.add_argument("--config", type=Path, help="validation configuration (.json or .toml)")
|
|
129
|
+
c.add_argument("--area-unit", choices=("m2", "ft2"), default="m2")
|
|
130
|
+
c.add_argument("--min-severity", choices=SEVERITIES, default="info")
|
|
131
|
+
c.add_argument("--output", "-o", type=Path, help="write the report to this file (default: stdout)")
|
|
132
|
+
c.set_defaults(handler=cmd_report)
|
|
133
|
+
|
|
134
|
+
c = model_cmd("ids", "Identifier map: GlobalId, UUID, STEP id, class, name, tag.")
|
|
135
|
+
c.add_argument("--csv", action="store_true")
|
|
136
|
+
_output_options(c)
|
|
137
|
+
c.set_defaults(handler=cmd_ids)
|
|
138
|
+
|
|
139
|
+
c = sub.add_parser("bcf", help="Read topic metadata from a BCF 2.1 / 3.0 archive.")
|
|
140
|
+
c.add_argument("file", type=Path)
|
|
141
|
+
c.add_argument("--no-people", action="store_true", help="redact author and assignee fields")
|
|
142
|
+
_output_options(c)
|
|
143
|
+
c.set_defaults(handler=cmd_bcf)
|
|
144
|
+
|
|
145
|
+
c = sub.add_parser("manifest", help="Create or check an asset manifest.")
|
|
146
|
+
msub = c.add_subparsers(title="actions", metavar="<action>")
|
|
147
|
+
mc = msub.add_parser("create", help="Hash the files under a folder into a manifest.")
|
|
148
|
+
mc.add_argument("root", type=Path)
|
|
149
|
+
mc.add_argument("--output", "-o", type=Path, help="manifest file (default: stdout)")
|
|
150
|
+
mc.set_defaults(handler=cmd_manifest_create)
|
|
151
|
+
mk = msub.add_parser("check", help="Check a manifest against its files and optionally an IFC model.")
|
|
152
|
+
mk.add_argument("manifest", type=Path)
|
|
153
|
+
mk.add_argument("--root", type=Path, help="folder the manifest paths are relative to")
|
|
154
|
+
mk.add_argument("--model", type=Path, help="IFC model whose GlobalIds the links must exist in")
|
|
155
|
+
mk.set_defaults(handler=cmd_manifest_check)
|
|
156
|
+
|
|
157
|
+
c = sub.add_parser("convert", help="Convert a length, area or volume between metric and imperial units.")
|
|
158
|
+
c.add_argument("value", type=float)
|
|
159
|
+
c.add_argument("from_unit")
|
|
160
|
+
c.add_argument("to_unit")
|
|
161
|
+
c.set_defaults(handler=cmd_convert)
|
|
162
|
+
|
|
163
|
+
c = sub.add_parser("rules", help="List the validation rules and their default severities.")
|
|
164
|
+
c.add_argument("--json", action="store_true")
|
|
165
|
+
c.set_defaults(handler=cmd_rules)
|
|
166
|
+
return p
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _load_options(c: argparse.ArgumentParser) -> None:
|
|
170
|
+
c.add_argument(
|
|
171
|
+
"--max-size-mb",
|
|
172
|
+
type=float,
|
|
173
|
+
default=DEFAULT_MAX_BYTES / 1024 / 1024,
|
|
174
|
+
help="refuse files larger than this (default: 256)",
|
|
175
|
+
)
|
|
176
|
+
c.add_argument(
|
|
177
|
+
"--allow-untested-schema",
|
|
178
|
+
action="store_true",
|
|
179
|
+
help="open schemas other than IFC2X3 / IFC4 (results not verified)",
|
|
180
|
+
)
|
|
181
|
+
c.add_argument(
|
|
182
|
+
"--redact-header",
|
|
183
|
+
action="store_true",
|
|
184
|
+
help="replace author / organisation names from the IFC header with '(redacted)' in the output",
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _output_options(c: argparse.ArgumentParser) -> None:
|
|
189
|
+
c.add_argument("--json", action="store_true", help="machine-readable JSON output")
|
|
190
|
+
c.add_argument("--output", "-o", type=Path, help="write the output to this file instead of stdout")
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _load(args: argparse.Namespace, path: Path) -> Any:
|
|
194
|
+
from bimora.ifc.extract import read_model
|
|
195
|
+
|
|
196
|
+
if args.max_size_mb <= 0:
|
|
197
|
+
raise ValueError("--max-size-mb must be positive")
|
|
198
|
+
return read_model(
|
|
199
|
+
path,
|
|
200
|
+
max_bytes=int(args.max_size_mb * 1024 * 1024),
|
|
201
|
+
allow_untested_schema=args.allow_untested_schema,
|
|
202
|
+
redact_header=args.redact_header,
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
# ── output ───────────────────────────────────────────────────────────────────
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _emit(args: argparse.Namespace, data: Any, text: str | None = None) -> None:
|
|
210
|
+
"""Write JSON (``--json`` or ``--output *.json``) or text to ``--output`` or stdout."""
|
|
211
|
+
out: Path | None = getattr(args, "output", None)
|
|
212
|
+
as_json = (
|
|
213
|
+
getattr(args, "json", False) or text is None or (out is not None and out.suffix.lower() == ".json")
|
|
214
|
+
)
|
|
215
|
+
payload = json.dumps(data, indent=2, ensure_ascii=False) + "\n" if as_json else (text or "") + "\n"
|
|
216
|
+
_write(out, payload)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _write(out: Path | None, payload: str) -> None:
|
|
220
|
+
if out is None:
|
|
221
|
+
sys.stdout.write(payload)
|
|
222
|
+
return
|
|
223
|
+
if out.exists() and out.is_dir():
|
|
224
|
+
raise _OutputError(f"{out} is a directory.")
|
|
225
|
+
try:
|
|
226
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
227
|
+
out.write_text(payload, encoding="utf-8", newline="")
|
|
228
|
+
except OSError as exc:
|
|
229
|
+
raise _OutputError(f"cannot write {out}: {exc.strerror or exc}") from exc
|
|
230
|
+
print(f"wrote {out}", file=sys.stderr)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
# ── commands ─────────────────────────────────────────────────────────────────
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def cmd_inspect(args: argparse.Namespace) -> int:
|
|
237
|
+
from bimora.reporting.report import inspection_summary, render_text
|
|
238
|
+
|
|
239
|
+
summary = inspection_summary(_load(args, args.file))
|
|
240
|
+
_emit(args, summary, render_text(summary))
|
|
241
|
+
return EXIT_OK
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def cmd_validate(args: argparse.Namespace) -> int:
|
|
245
|
+
from bimora.validation.engine import validate
|
|
246
|
+
|
|
247
|
+
result = validate(_load(args, args.file), args.config)
|
|
248
|
+
data = result.to_dict(args.min_severity)
|
|
249
|
+
lines = [
|
|
250
|
+
f"{result.file_name}: " + ", ".join(f"{n} {s}" for s, n in reversed(result.counts.items())),
|
|
251
|
+
data["disclaimer"],
|
|
252
|
+
"",
|
|
253
|
+
]
|
|
254
|
+
for f in result.at_least(args.min_severity):
|
|
255
|
+
where = f"{f.ifc_class or 'model'} {f.element_id or ''}".strip()
|
|
256
|
+
lines.append(f"[{f.severity.upper():7}] {f.rule_id} {where}: {f.description}")
|
|
257
|
+
lines.append(f" -> {f.recommendation}")
|
|
258
|
+
_emit(args, data, "\n".join(lines))
|
|
259
|
+
if args.fail_on != "never" and result.at_least(args.fail_on):
|
|
260
|
+
return EXIT_CHECK_FAILED
|
|
261
|
+
return EXIT_OK
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def cmd_spaces(args: argparse.Namespace) -> int:
|
|
265
|
+
from bimora.interoperability.csv_export import to_csv
|
|
266
|
+
from bimora.spatial.analysis import area_summary, room_inventory
|
|
267
|
+
|
|
268
|
+
model = _load(args, args.file)
|
|
269
|
+
rooms = room_inventory(model)
|
|
270
|
+
if args.csv:
|
|
271
|
+
flat = [
|
|
272
|
+
{k: v for k, v in r.items() if k not in ("NetFloorArea", "GrossFloorArea")}
|
|
273
|
+
| {f"{q}": (r[q]["value"] if r[q] else None) for q in ("NetFloorArea", "GrossFloorArea")}
|
|
274
|
+
| {"area_unit": next((r[q]["unit"] for q in ("NetFloorArea", "GrossFloorArea") if r[q]), None)}
|
|
275
|
+
for r in rooms
|
|
276
|
+
]
|
|
277
|
+
fields = [
|
|
278
|
+
"global_id",
|
|
279
|
+
"number",
|
|
280
|
+
"name",
|
|
281
|
+
"storey",
|
|
282
|
+
"category",
|
|
283
|
+
"NetFloorArea",
|
|
284
|
+
"GrossFloorArea",
|
|
285
|
+
"area_unit",
|
|
286
|
+
]
|
|
287
|
+
_write(args.output, to_csv(flat, fields))
|
|
288
|
+
return EXIT_OK
|
|
289
|
+
areas = area_summary(model, args.area_unit)
|
|
290
|
+
lines = [f"{'Number':<10}{'Name':<24}{'Storey':<18}{'Net area':>14}{'Gross area':>14}"]
|
|
291
|
+
for r in rooms:
|
|
292
|
+
net, gross = r["NetFloorArea"], r["GrossFloorArea"]
|
|
293
|
+
lines.append(
|
|
294
|
+
f"{(r['number'] or '-'):<10}{(r['name'] or '-')[:23]:<24}{(r['storey'] or '-')[:17]:<18}"
|
|
295
|
+
f"{_q(net):>14}{_q(gross):>14}"
|
|
296
|
+
)
|
|
297
|
+
lines.append(
|
|
298
|
+
f"Totals ({areas['calculated']}, {args.area_unit}): net {areas['total']['NetFloorArea']}, gross {areas['total']['GrossFloorArea']}"
|
|
299
|
+
)
|
|
300
|
+
if areas["spaces_without_declared_area"]:
|
|
301
|
+
lines.append(f"Spaces without a declared area: {len(areas['spaces_without_declared_area'])}")
|
|
302
|
+
_emit(args, {"rooms": rooms, "areas": areas}, "\n".join(lines))
|
|
303
|
+
return EXIT_OK
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _q(q: dict[str, Any] | None) -> str:
|
|
307
|
+
return "-" if not q or q["value"] is None else f"{q['value']:g} {q['unit'] or ''}".strip()
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def cmd_properties(args: argparse.Namespace) -> int:
|
|
311
|
+
from bimora.interoperability.csv_export import PROPERTY_FIELDS, property_rows, to_csv
|
|
312
|
+
|
|
313
|
+
rows = property_rows(_load(args, args.file))
|
|
314
|
+
if args.ifc_class:
|
|
315
|
+
rows = [r for r in rows if r["ifc_class"] == args.ifc_class]
|
|
316
|
+
if args.pset:
|
|
317
|
+
rows = [r for r in rows if r["property_set"] == args.pset]
|
|
318
|
+
if args.csv:
|
|
319
|
+
_write(args.output, to_csv(rows, PROPERTY_FIELDS))
|
|
320
|
+
return EXIT_OK
|
|
321
|
+
text = "\n".join(
|
|
322
|
+
f"{r['global_id']} {r['ifc_class']:<16} {r['property_set']}.{r['property']} = {r['value']!r}"
|
|
323
|
+
for r in rows
|
|
324
|
+
)
|
|
325
|
+
_emit(args, rows, text or "(no properties)")
|
|
326
|
+
return EXIT_OK
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def cmd_export(args: argparse.Namespace) -> int:
|
|
330
|
+
from bimora.interoperability import csv_export, json_export, mapping
|
|
331
|
+
|
|
332
|
+
model = _load(args, args.file)
|
|
333
|
+
if args.mapping:
|
|
334
|
+
if args.format != "csv":
|
|
335
|
+
raise ValueError("--mapping is only used with --format csv")
|
|
336
|
+
out = args.output or Path(f"{Path(model.file_name).stem}.mapped.csv")
|
|
337
|
+
if out.is_dir():
|
|
338
|
+
out = out / f"{Path(model.file_name).stem}.mapped.csv"
|
|
339
|
+
try:
|
|
340
|
+
path = mapping.export_mapped_csv(model, mapping.load_mapping(args.mapping), out)
|
|
341
|
+
except OSError as exc:
|
|
342
|
+
raise _OutputError(f"cannot write {out}: {exc}") from exc
|
|
343
|
+
print(f"wrote {path}", file=sys.stderr)
|
|
344
|
+
return EXIT_OK
|
|
345
|
+
if args.format == "json":
|
|
346
|
+
_write(args.output, json.dumps(json_export.model_to_json(model), indent=2, ensure_ascii=False) + "\n")
|
|
347
|
+
return EXIT_OK
|
|
348
|
+
target = args.output or Path(".")
|
|
349
|
+
if target.exists() and not target.is_dir():
|
|
350
|
+
raise _OutputError(
|
|
351
|
+
f"{target} exists and is not a directory (CSV export writes three files into a directory)."
|
|
352
|
+
)
|
|
353
|
+
try:
|
|
354
|
+
paths = csv_export.export_csv(model, target)
|
|
355
|
+
except OSError as exc:
|
|
356
|
+
raise _OutputError(f"cannot write into {target}: {exc}") from exc
|
|
357
|
+
for p in paths.values():
|
|
358
|
+
print(f"wrote {p}", file=sys.stderr)
|
|
359
|
+
return EXIT_OK
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def cmd_compare(args: argparse.Namespace) -> int:
|
|
363
|
+
from bimora.interoperability.compare import compare_models
|
|
364
|
+
|
|
365
|
+
result = compare_models(_load(args, args.before), _load(args, args.after))
|
|
366
|
+
s = result.summary
|
|
367
|
+
lines = [
|
|
368
|
+
f"{result.file_a} -> {result.file_b} (metadata by GlobalId; not geometry / clash detection)",
|
|
369
|
+
f"added {s['added']}, removed {s['removed']}, changed {s['changed']}, unchanged {s['unchanged']}",
|
|
370
|
+
]
|
|
371
|
+
lines += [f"warning: {w}" for w in result.warnings]
|
|
372
|
+
lines += [f"+ {a['ifc_class']} {a['global_id']} {a['name'] or ''}" for a in result.added]
|
|
373
|
+
lines += [f"- {r['ifc_class']} {r['global_id']} {r['name'] or ''}" for r in result.removed]
|
|
374
|
+
for d in result.changed:
|
|
375
|
+
lines.append(f"~ {d.ifc_class} {d.global_id} {d.name or ''}")
|
|
376
|
+
lines += [f" {c.field}: {c.before!r} -> {c.after!r}" for c in d.changes]
|
|
377
|
+
_emit(args, result.to_dict(), "\n".join(lines))
|
|
378
|
+
changed = s["added"] or s["removed"] or s["changed"]
|
|
379
|
+
return EXIT_CHECK_FAILED if args.fail_on_changes and changed else EXIT_OK
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def cmd_report(args: argparse.Namespace) -> int:
|
|
383
|
+
from bimora.reporting.report import build_report
|
|
384
|
+
from bimora.validation.engine import validate
|
|
385
|
+
|
|
386
|
+
model = _load(args, args.file)
|
|
387
|
+
doc = build_report(
|
|
388
|
+
model, validate(model, args.config), area_unit=args.area_unit, min_severity=args.min_severity
|
|
389
|
+
)
|
|
390
|
+
_write(args.output, json.dumps(doc, indent=2, ensure_ascii=False) + "\n")
|
|
391
|
+
return EXIT_OK
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def cmd_ids(args: argparse.Namespace) -> int:
|
|
395
|
+
from bimora.interoperability.csv_export import to_csv
|
|
396
|
+
from bimora.interoperability.identifiers import identifier_map
|
|
397
|
+
|
|
398
|
+
rows = identifier_map(_load(args, args.file))
|
|
399
|
+
if args.csv:
|
|
400
|
+
_write(args.output, to_csv(rows, ["global_id", "uuid", "step_id", "ifc_class", "name", "tag"]))
|
|
401
|
+
return EXIT_OK
|
|
402
|
+
_emit(
|
|
403
|
+
args,
|
|
404
|
+
rows,
|
|
405
|
+
"\n".join(
|
|
406
|
+
f"{r['global_id']} {r['uuid']} #{r['step_id']:<6} {r['ifc_class']:<20} {r['name'] or ''}"
|
|
407
|
+
for r in rows
|
|
408
|
+
),
|
|
409
|
+
)
|
|
410
|
+
return EXIT_OK
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def cmd_bcf(args: argparse.Namespace) -> int:
|
|
414
|
+
from bimora.interoperability.bcf import read_bcf
|
|
415
|
+
|
|
416
|
+
summary = read_bcf(args.file)
|
|
417
|
+
data = summary.to_dict(include_people=not args.no_people)
|
|
418
|
+
lines = [f"{summary.file_name}: BCF {summary.version or '?'}, {len(summary.topics)} topic(s)"]
|
|
419
|
+
for t in data["topics"]:
|
|
420
|
+
lines.append(
|
|
421
|
+
f" [{t['status'] or '-'}] {t['title'] or '(untitled)'} - {t['comment_count']} comment(s), {len(t['referenced_guids'])} element(s)"
|
|
422
|
+
)
|
|
423
|
+
lines += [f"warning: {w}" for w in summary.warnings]
|
|
424
|
+
_emit(args, data, "\n".join(lines))
|
|
425
|
+
return EXIT_OK
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def cmd_manifest_create(args: argparse.Namespace) -> int:
|
|
429
|
+
from bimora.interoperability.manifest import create_manifest
|
|
430
|
+
|
|
431
|
+
_write(args.output, json.dumps(create_manifest(args.root), indent=2) + "\n")
|
|
432
|
+
return EXIT_OK
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def cmd_manifest_check(args: argparse.Namespace) -> int:
|
|
436
|
+
from bimora.errors import ConfigError
|
|
437
|
+
from bimora.ifc.extract import read_model
|
|
438
|
+
from bimora.interoperability.manifest import check_manifest
|
|
439
|
+
|
|
440
|
+
try:
|
|
441
|
+
manifest = json.loads(args.manifest.read_text(encoding="utf-8"))
|
|
442
|
+
except FileNotFoundError as exc:
|
|
443
|
+
raise ConfigError(f"{args.manifest}: file not found.") from exc
|
|
444
|
+
except json.JSONDecodeError as exc:
|
|
445
|
+
raise ConfigError(f"{args.manifest.name}: invalid JSON ({exc}).") from exc
|
|
446
|
+
model = read_model(args.model) if args.model else None
|
|
447
|
+
problems = check_manifest(manifest, root=args.root, model=model)
|
|
448
|
+
for p in problems:
|
|
449
|
+
print(p)
|
|
450
|
+
print(f"{len(problems)} problem(s)", file=sys.stderr)
|
|
451
|
+
return EXIT_CHECK_FAILED if problems else EXIT_OK
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def cmd_convert(args: argparse.Namespace) -> int:
|
|
455
|
+
from bimora.spatial.units import convert
|
|
456
|
+
|
|
457
|
+
print(f"{convert(args.value, args.from_unit, args.to_unit):.10g} {args.to_unit}")
|
|
458
|
+
return EXIT_OK
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def cmd_rules(args: argparse.Namespace) -> int:
|
|
462
|
+
from bimora.validation.engine import rule_catalog
|
|
463
|
+
|
|
464
|
+
rules = rule_catalog()
|
|
465
|
+
if args.json:
|
|
466
|
+
print(json.dumps(rules, indent=2))
|
|
467
|
+
else:
|
|
468
|
+
for r in rules:
|
|
469
|
+
print(f"{r['rule_id']} {r['default_severity']:<8} {r['title']}")
|
|
470
|
+
return EXIT_OK
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
if __name__ == "__main__": # pragma: no cover
|
|
474
|
+
raise SystemExit(main())
|
bimora/errors.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Exception hierarchy. Every error raised on purpose by the toolkit derives from :class:`BimoraError`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class BimoraError(Exception):
|
|
7
|
+
"""Base class for toolkit errors."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class InputError(BimoraError):
|
|
11
|
+
"""The input path or file is not usable (missing, a directory, wrong type, too large)."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class UnsupportedFormatError(InputError):
|
|
15
|
+
"""The file is not a supported format (for example IFC-ZIP, ifcXML or a non-IFC file)."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class UnsupportedSchemaError(InputError):
|
|
19
|
+
"""The IFC schema has not been verified with this release."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class FileTooLargeError(InputError):
|
|
23
|
+
"""The file exceeds the configured size limit."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class ParseError(InputError):
|
|
27
|
+
"""The file looks like IFC but could not be parsed."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ConfigError(BimoraError):
|
|
31
|
+
"""A configuration file (validation rules, field mapping) is invalid."""
|
bimora/ifc/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""IFC loading and extraction."""
|