mirror of
https://github.com/IfcOpenShell/IfcOpenShell.git
synced 2026-08-08 17:01:40 +00:00
Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e42acdfa86 | |||
| 1801a768c1 | |||
| 66f0b71c65 | |||
| f4d7fda255 | |||
| c112c115ce | |||
| 2a2ba45676 | |||
| fd69c0534b | |||
| 1226370b9e | |||
| 6e3eaa9b39 | |||
| 3ed2da23be | |||
| 249c498112 | |||
| 2dde62803d |
@@ -0,0 +1,153 @@
|
||||
<!-- This file was generated with the assistance of an AI coding tool. -->
|
||||
|
||||
# AGENTS.md
|
||||
|
||||
Guidelines for AI coding agents contributing to IfcOpenShell. This file is
|
||||
intended to be read by all AI agents regardless of platform (Claude Code,
|
||||
Copilot, Cursor, etc.) in addition to any tool-specific configuration files.
|
||||
|
||||
Human contributors using AI tools should also read this document carefully,
|
||||
as they are responsible for ensuring their contributions comply with these
|
||||
guidelines.
|
||||
|
||||
## Project Overview
|
||||
|
||||
IfcOpenShell is an open source library for working with Industry Foundation
|
||||
Classes (IFC). It provides C++ and Python APIs, geometry processing, and an
|
||||
ecosystem of tools including IfcConvert and the Bonsai Blender add-on.
|
||||
|
||||
## Licensing
|
||||
|
||||
All contributions must be compatible with the project's licensing:
|
||||
|
||||
- **Library code** (everything except Bonsai): **LGPL-3.0-or-later**
|
||||
- **Bonsai** (`src/bonsai/`): **GPL-3.0-or-later**
|
||||
|
||||
There is no Contributor License Agreement (CLA). By submitting a pull request,
|
||||
you agree that your contribution is licensed under the applicable license above.
|
||||
|
||||
## Indicating AI-Generated Code
|
||||
|
||||
Contributors must clearly indicate when code has been generated or
|
||||
substantially written by an AI tool.
|
||||
|
||||
### Commits
|
||||
|
||||
Commits that modify existing code must include a note in the **body** of the
|
||||
commit message (not the subject line) indicating that the change was
|
||||
AI-generated. For example:
|
||||
|
||||
```
|
||||
Fix off-by-one error in element iteration
|
||||
|
||||
The loop termination condition was incorrect when processing
|
||||
IfcRelAggregates relationships.
|
||||
|
||||
Generated with the assistance of an AI coding tool.
|
||||
```
|
||||
|
||||
### New Files
|
||||
|
||||
New files that are AI-generated must include a comment near the top of the
|
||||
file indicating this. Use the appropriate comment syntax for the language:
|
||||
|
||||
```python
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
```
|
||||
|
||||
```cpp
|
||||
// This file was generated with the assistance of an AI coding tool.
|
||||
```
|
||||
|
||||
### Pull Requests
|
||||
|
||||
Pull requests containing AI-generated code must indicate in the PR description
|
||||
which parts of the contribution are AI-generated. If the entire PR is
|
||||
AI-generated, state that clearly. If only specific commits or files are
|
||||
AI-generated, identify them.
|
||||
|
||||
## Pull Request Guidelines
|
||||
|
||||
### Scope and Size
|
||||
|
||||
- Each pull request should address a **single issue or feature**.
|
||||
- Do not mix unrelated changes (e.g., bug fixes with refactoring or style
|
||||
changes) in the same PR.
|
||||
- Large pull requests should be broken down into **multiple small, standalone
|
||||
commits** that are each easy to review independently. Rewrite commit history
|
||||
for this purpose if necessary.
|
||||
- PRs that are minimal, focused solutions to a specific problem are much more
|
||||
likely to be accepted.
|
||||
|
||||
### What to Avoid
|
||||
|
||||
- **Over-engineering**: Do not add features, abstractions, or configurability
|
||||
beyond what is needed to solve the immediate problem.
|
||||
- **Scope creep**: Do not make changes to files or code that are not directly
|
||||
related to the task at hand.
|
||||
- **Unnecessary additions**: Do not add docstrings, comments, type annotations,
|
||||
or error handling to code you did not otherwise need to change.
|
||||
- **Cosmetic changes**: Do not reformat, rename, or reorganize code that is
|
||||
unrelated to your change.
|
||||
|
||||
## Commit Messages
|
||||
|
||||
- The **subject line** must be **50 characters or less**.
|
||||
- Use the **imperative mood** (e.g., "Fix crash in geometry kernel", not
|
||||
"Fixed crash" or "Fixes crash").
|
||||
- A commit message can be a single line if the purpose is obvious from the
|
||||
subject alone.
|
||||
- Otherwise, add a blank line after the subject followed by a short explanation
|
||||
of a few lines in the body.
|
||||
|
||||
## Code Style
|
||||
|
||||
### Python
|
||||
|
||||
- **Line length**: 120 characters
|
||||
- **Formatter**: black
|
||||
- **Linter**: ruff
|
||||
- Configuration is in `pyproject.toml`
|
||||
|
||||
### C++
|
||||
|
||||
- **Standard**: C++17 minimum
|
||||
- **Formatter**: clang-format (configuration in `.clang-format`)
|
||||
- **Linter**: clang-tidy (configuration in `.clang-tidy`)
|
||||
|
||||
Run linters and formatters **before submitting** your pull request. Do not rely
|
||||
on CI to catch formatting issues.
|
||||
|
||||
## Testing
|
||||
|
||||
- Pull requests with test coverage are **much more likely to be merged**.
|
||||
- If tests are appropriate and feasible for your change, they should be
|
||||
included.
|
||||
- Tests are not required for every change (e.g., documentation-only changes),
|
||||
but the expectation is that testable code changes come with tests.
|
||||
- Python tests use **pytest** and are located in `test/` or `tests/` directories
|
||||
within each package under `src/`.
|
||||
- Run the existing test suite for the package you modified before submitting.
|
||||
|
||||
## Architecture Quick Reference
|
||||
|
||||
### Directory Structure
|
||||
|
||||
- `src/ifcparse/` — C++ IFC file parsing
|
||||
- `src/ifcgeom/` — C++ geometry processing (OpenCASCADE and CGAL kernels)
|
||||
- `src/serializers/` — Output format serializers (glTF, Collada, SVG, etc.)
|
||||
- `src/ifcwrap/` — SWIG Python bindings
|
||||
- `src/ifcconvert/` — CLI conversion tool
|
||||
- `src/ifcopenshell-python/` — Python API (`ifcopenshell` package)
|
||||
- `src/bonsai/` — Blender add-on (GPL-3.0-or-later)
|
||||
- `src/ifctester/` — IDS model auditing
|
||||
- `src/ifcpatch/` — IFC file manipulation scripts
|
||||
- `src/ifcdiff/` — IFC model comparison
|
||||
- `src/ifcclash/` — Clash detection
|
||||
- `src/ifccsv/` — Schedule import/export
|
||||
|
||||
### IFC Schema Versions
|
||||
|
||||
The library supports IFC2x3 TC1, IFC4 Add2 TC1, IFC4x1, IFC4x2, and
|
||||
IFC4x3 Add2. Schema-specific code is compiled conditionally. Be aware of
|
||||
which schema versions your change affects.
|
||||
@@ -124,6 +124,26 @@ const tools = [
|
||||
type: "function", name: "ifc_edit", description: "Execute an ifcopenshell.api mutation; params is a JSON string of stringly-typed kwargs.",
|
||||
parameters: { type: "object", properties: { function_path: { type: "string" }, params: { type: "string" } }, required: ["function_path"], additionalProperties: false }
|
||||
},
|
||||
{
|
||||
type: "function", name: "ifc_validate", description: "Validate the loaded model. Returns valid bool and list of issues.",
|
||||
parameters: { type: "object", properties: { express_rules: { type: "boolean" } }, required: [], additionalProperties: false }
|
||||
},
|
||||
{
|
||||
type: "function", name: "ifc_schedule", description: "List work schedules and nested tasks. Use max_depth=1 for top-level phases only on large projects.",
|
||||
parameters: { type: "object", properties: { max_depth: { type: "integer" } }, required: [], additionalProperties: false }
|
||||
},
|
||||
{
|
||||
type: "function", name: "ifc_cost", description: "List cost schedules and nested cost items. Use max_depth=1 for top-level sections only on large BoQs.",
|
||||
parameters: { type: "object", properties: { max_depth: { type: "integer" } }, required: [], additionalProperties: false }
|
||||
},
|
||||
{
|
||||
type: "function", name: "ifc_schema", description: "Return IFC class documentation for an entity type.",
|
||||
parameters: { type: "object", properties: { entity_type: { type: "string" } }, required: ["entity_type"], additionalProperties: false }
|
||||
},
|
||||
{
|
||||
type: "function", name: "ifc_quantify", description: "Run quantity take-off (QTO) on the model. Modifies model in-place; call ifc_save() after.",
|
||||
parameters: { type: "object", properties: { rule: { type: "string" }, selector: { type: "string" } }, required: ["rule"], additionalProperties: false }
|
||||
},
|
||||
];
|
||||
|
||||
const SYSTEM_INSTRUCTIONS = `
|
||||
+41
-2
@@ -181,6 +181,45 @@ ifcedit run model.ifc pset.edit_pset --pset 15 \
|
||||
--properties '{"IsExternal": true, "FireRating": "2HR"}'
|
||||
```
|
||||
|
||||
### quantify
|
||||
|
||||
Run quantity take-off (QTO) on an IFC file, computing physical measurements
|
||||
(volume, area, length, count, weight) and writing them back as
|
||||
`IfcElementQuantity` property sets. Uses `ifc5d` rules.
|
||||
|
||||
**List available rules:**
|
||||
|
||||
```bash
|
||||
ifcedit quantify list
|
||||
```
|
||||
|
||||
```json
|
||||
[
|
||||
{"name": "IFC4QtoBaseQuantities"},
|
||||
{"name": "IFC4X3QtoBaseQuantities"}
|
||||
]
|
||||
```
|
||||
|
||||
**Run QTO on a file:**
|
||||
|
||||
```bash
|
||||
ifcedit quantify run model.ifc IFC4QtoBaseQuantities
|
||||
ifcedit quantify run model.ifc IFC4QtoBaseQuantities --selector IfcWall
|
||||
ifcedit quantify run model.ifc IFC4QtoBaseQuantities -o model_qto.ifc
|
||||
```
|
||||
|
||||
```json
|
||||
{"ok": true, "rule": "IFC4QtoBaseQuantities", "elements_quantified": 42}
|
||||
```
|
||||
|
||||
Options:
|
||||
|
||||
- `--selector <query>` -- ifcopenshell selector to restrict elements (default: all `IfcElement`)
|
||||
- `-o, --output <path>` -- write to a different file instead of overwriting the input
|
||||
|
||||
Note: `quantify run` writes geometry-based measurements and requires the
|
||||
IfcOpenShell C++ geometry bindings for elements with computed quantities.
|
||||
|
||||
## Error handling
|
||||
|
||||
Errors are reported in the JSON response:
|
||||
@@ -198,8 +237,8 @@ Exit code is 0 on success, 1 on error.
|
||||
|
||||
`ifcedit` and `ifcquery` are complementary tools:
|
||||
|
||||
- **ifcquery** reads and inspects IFC models (summary, tree, info, select, relations, clash)
|
||||
- **ifcedit** modifies IFC models by wrapping `ifcopenshell.api` functions
|
||||
- **ifcquery** reads and inspects IFC models (summary, tree, info, select, relations, clash, validate, schedule, cost, schema)
|
||||
- **ifcedit** modifies IFC models by wrapping `ifcopenshell.api` functions, and runs QTO via `quantify`
|
||||
|
||||
A typical workflow: inspect with `ifcquery`, look up the right API function
|
||||
with `ifcedit docs`, then apply changes with `ifcedit run`.
|
||||
|
||||
@@ -26,6 +26,7 @@ import sys
|
||||
import ifcopenshell
|
||||
|
||||
from ifcedit.discover import function_docs, list_functions, list_modules
|
||||
from ifcedit.quantify import list_rules, run_quantify
|
||||
from ifcedit.run import run_api
|
||||
|
||||
|
||||
@@ -137,6 +138,29 @@ def _parse_extra_args(extra: list[str]) -> dict[str, str]:
|
||||
return kwargs
|
||||
|
||||
|
||||
def cmd_quantify(args, extra_args):
|
||||
if args.quantify_command == "list":
|
||||
result = list_rules()
|
||||
print(format_output(result, args.output_format))
|
||||
elif args.quantify_command == "run":
|
||||
try:
|
||||
model = ifcopenshell.open(args.ifc_file)
|
||||
except Exception as e:
|
||||
print(f"Error: Could not open IFC file: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
selector = args.selector or None
|
||||
result = run_quantify(model, args.rule_name, selector=selector)
|
||||
if result["ok"]:
|
||||
output_path = args.output or args.ifc_file
|
||||
model.write(output_path)
|
||||
print(format_output(result, args.output_format))
|
||||
if not result["ok"]:
|
||||
sys.exit(1)
|
||||
else:
|
||||
print("Error: quantify requires a subcommand: list or run", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="ifcedit",
|
||||
@@ -167,6 +191,16 @@ def main():
|
||||
run_parser.add_argument("-o", "--output", help="Output file path (default: overwrite input)")
|
||||
run_parser.add_argument("--dry-run", action="store_true", help="Validate without executing or saving")
|
||||
|
||||
# quantify
|
||||
quantify_parser = subparsers.add_parser("quantify", help="Quantity take-off (QTO) using ifc5d rules")
|
||||
quantify_sub = quantify_parser.add_subparsers(dest="quantify_command")
|
||||
quantify_sub.add_parser("list", help="List available QTO rule names")
|
||||
qrun_parser = quantify_sub.add_parser("run", help="Run QTO on an IFC file")
|
||||
qrun_parser.add_argument("ifc_file", help="Path to the IFC file")
|
||||
qrun_parser.add_argument("rule_name", help="QTO rule name (e.g. IFC4QtoBaseQuantities)")
|
||||
qrun_parser.add_argument("--selector", help="ifcopenshell selector to restrict elements (default: all IfcElement)")
|
||||
qrun_parser.add_argument("-o", "--output", help="Output file path (default: overwrite input)")
|
||||
|
||||
args, extra = parser.parse_known_args()
|
||||
|
||||
if args.command == "list":
|
||||
@@ -175,6 +209,8 @@ def main():
|
||||
cmd_docs(args)
|
||||
elif args.command == "run":
|
||||
cmd_run(args, extra)
|
||||
elif args.command == "quantify":
|
||||
cmd_quantify(args, extra)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -25,13 +25,21 @@ import typing
|
||||
import ifcopenshell
|
||||
|
||||
|
||||
def coerce_value(value_str: str, type_hint, model: ifcopenshell.file | None = None):
|
||||
def coerce_value(
|
||||
value_str: str,
|
||||
type_hint,
|
||||
model: ifcopenshell.file | None = None,
|
||||
lookup_file: ifcopenshell.file | None = None,
|
||||
):
|
||||
"""Convert a CLI string argument to the proper Python type based on a type hint.
|
||||
|
||||
Args:
|
||||
value_str: The raw string from the CLI.
|
||||
type_hint: The type annotation from the function signature.
|
||||
model: An open IFC model, needed to resolve entity instance references by ID.
|
||||
model: The main open IFC model, needed to resolve entity instance references by ID.
|
||||
lookup_file: Override file for entity resolution (e.g. a library file for
|
||||
project.append_asset). When provided, entity IDs are looked up here instead
|
||||
of in model.
|
||||
|
||||
Returns:
|
||||
The converted Python value.
|
||||
@@ -40,6 +48,9 @@ def coerce_value(value_str: str, type_hint, model: ifcopenshell.file | None = No
|
||||
ValueError: If the value cannot be converted.
|
||||
TypeError: If the type hint is not supported.
|
||||
"""
|
||||
# When a library file has been opened, entity IDs are resolved from it, not the main model.
|
||||
effective_lookup = lookup_file if lookup_file is not None else model
|
||||
|
||||
if type_hint is None:
|
||||
return value_str
|
||||
|
||||
@@ -55,7 +66,7 @@ def coerce_value(value_str: str, type_hint, model: ifcopenshell.file | None = No
|
||||
# Try each non-None type in order
|
||||
for t in non_none_types:
|
||||
try:
|
||||
return coerce_value(value_str, t, model)
|
||||
return coerce_value(value_str, t, model, lookup_file)
|
||||
except (ValueError, TypeError):
|
||||
continue
|
||||
raise ValueError(f"Cannot convert '{value_str}' to any of {non_none_types}")
|
||||
@@ -73,10 +84,10 @@ def coerce_value(value_str: str, type_hint, model: ifcopenshell.file | None = No
|
||||
# list types
|
||||
if origin is list:
|
||||
if args and _is_entity_type(args[0]):
|
||||
return _coerce_entity_list(value_str, model)
|
||||
return _coerce_entity_list(value_str, effective_lookup)
|
||||
if args:
|
||||
items = _split_list(value_str)
|
||||
return [coerce_value(item.strip(), args[0], model) for item in items]
|
||||
return [coerce_value(item.strip(), args[0], model, lookup_file) for item in items]
|
||||
return _split_list(value_str)
|
||||
|
||||
# dict types
|
||||
@@ -93,9 +104,13 @@ def coerce_value(value_str: str, type_hint, model: ifcopenshell.file | None = No
|
||||
if type_hint is bool:
|
||||
return value_str.lower() in ("true", "1", "yes")
|
||||
|
||||
# ifcopenshell.file — open from path string
|
||||
if type_hint is ifcopenshell.file:
|
||||
return ifcopenshell.open(value_str)
|
||||
|
||||
# entity_instance
|
||||
if _is_entity_type(type_hint):
|
||||
return _coerce_entity(value_str, model)
|
||||
return _coerce_entity(value_str, effective_lookup)
|
||||
|
||||
# Fallback: try json.loads for complex types, then plain string
|
||||
try:
|
||||
@@ -113,24 +128,24 @@ def _is_entity_type(hint) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _coerce_entity(value_str: str | int, model: ifcopenshell.file | None) -> ifcopenshell.entity_instance:
|
||||
def _coerce_entity(value_str: str | int, lookup_file: ifcopenshell.file | None) -> ifcopenshell.entity_instance:
|
||||
"""Resolve a step ID string like '123' or '#123' to an entity instance."""
|
||||
if model is None:
|
||||
if lookup_file is None:
|
||||
raise ValueError("Cannot resolve entity reference without an IFC model")
|
||||
if isinstance(value_str, int):
|
||||
entity_id = value_str
|
||||
else:
|
||||
entity_id = int(value_str.strip().lstrip("#"))
|
||||
try:
|
||||
return model.by_id(entity_id)
|
||||
return lookup_file.by_id(entity_id)
|
||||
except RuntimeError:
|
||||
raise ValueError(f"Entity #{entity_id} not found in model")
|
||||
|
||||
|
||||
def _coerce_entity_list(value_str: str, model: ifcopenshell.file | None) -> list[ifcopenshell.entity_instance]:
|
||||
def _coerce_entity_list(value_str: str, lookup_file: ifcopenshell.file | None) -> list[ifcopenshell.entity_instance]:
|
||||
"""Resolve a comma-separated list of step IDs to entity instances."""
|
||||
items = _split_list(value_str)
|
||||
return [_coerce_entity(item.strip(), model) for item in items]
|
||||
return [_coerce_entity(item.strip(), lookup_file) for item in items]
|
||||
|
||||
|
||||
def _split_list(value_str: str) -> list[str]:
|
||||
@@ -140,7 +155,7 @@ def _split_list(value_str: str) -> list[str]:
|
||||
try:
|
||||
parsed = json.loads(value_str)
|
||||
if isinstance(parsed, list):
|
||||
return [str(item) for item in parsed]
|
||||
return [json.dumps(item) if isinstance(item, (dict, list)) else str(item) for item in parsed]
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
return [item.strip() for item in value_str.split(",") if item.strip()]
|
||||
|
||||
@@ -165,10 +165,15 @@ def _extract_params(fn) -> list[dict]:
|
||||
|
||||
def _format_type_hint(hint) -> str | None:
|
||||
"""Format a type hint to a readable string."""
|
||||
import ifcopenshell
|
||||
|
||||
if hint is None:
|
||||
return None
|
||||
if hint is type(None):
|
||||
return "None"
|
||||
# ifcopenshell.file params are passed as a file path string
|
||||
if hint is ifcopenshell.file:
|
||||
return "file_path"
|
||||
origin = typing.get_origin(hint)
|
||||
args = typing.get_args(hint)
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import ifcopenshell
|
||||
|
||||
AVAILABLE_RULES = ["IFC4QtoBaseQuantities", "IFC4X3QtoBaseQuantities"]
|
||||
|
||||
|
||||
def list_rules() -> list[dict[str, str]]:
|
||||
"""Return a list of available quantification rule names."""
|
||||
return [{"name": name} for name in AVAILABLE_RULES]
|
||||
|
||||
|
||||
def run_quantify(model: ifcopenshell.file, rule: str, selector: str | None = None) -> dict[str, Any]:
|
||||
"""Run quantity take-off on the model using the named rule.
|
||||
|
||||
Modifies the model in-place by adding/updating IfcElementQuantity psets.
|
||||
Returns a summary dict with ok, rule, and elements_quantified.
|
||||
"""
|
||||
from ifc5d.qto import edit_qtos, quantify
|
||||
from ifc5d.qto import rules as rule_sets
|
||||
|
||||
if rule not in rule_sets:
|
||||
return {"ok": False, "error": f"Unknown rule: {rule}. Available: {list(rule_sets.keys())}"}
|
||||
|
||||
import ifcopenshell.util.selector
|
||||
|
||||
if selector:
|
||||
elements = set(ifcopenshell.util.selector.filter_elements(model, selector))
|
||||
else:
|
||||
elements = set(model.by_type("IfcElement"))
|
||||
|
||||
results = quantify(model, elements, rule_sets[rule])
|
||||
edit_qtos(model, results)
|
||||
return {"ok": True, "rule": rule, "elements_quantified": len(results)}
|
||||
@@ -28,6 +28,17 @@ import ifcopenshell
|
||||
from ifcedit.coerce import coerce_value
|
||||
|
||||
|
||||
def _is_file_type(hint) -> bool:
|
||||
"""Check if a type hint refers to ifcopenshell.file (or Optional[ifcopenshell.file])."""
|
||||
if hint is ifcopenshell.file:
|
||||
return True
|
||||
origin = typing.get_origin(hint)
|
||||
args = typing.get_args(hint)
|
||||
if origin is typing.Union and ifcopenshell.file in args:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def run_api(
|
||||
model: ifcopenshell.file,
|
||||
module: str,
|
||||
@@ -58,12 +69,36 @@ def run_api(
|
||||
|
||||
sig = inspect.signature(fn)
|
||||
coerced_kwargs = {}
|
||||
|
||||
# Pass 1: coerce ifcopenshell.file-typed params first (e.g. library= in append_asset).
|
||||
# The opened file is then used as the lookup file for entity resolution in pass 2.
|
||||
opened_files: list[ifcopenshell.file] = []
|
||||
for name, value_str in raw_kwargs.items():
|
||||
if name not in sig.parameters:
|
||||
return {"ok": False, "error": f"Unknown parameter '{name}' for {module}.{function}"}
|
||||
hint = hints.get(name)
|
||||
if not _is_file_type(hint):
|
||||
continue
|
||||
try:
|
||||
coerced_kwargs[name] = coerce_value(value_str, hint, model)
|
||||
coerced = coerce_value(value_str, hint, model)
|
||||
coerced_kwargs[name] = coerced
|
||||
if isinstance(coerced, ifcopenshell.file):
|
||||
opened_files.append(coerced)
|
||||
except (ValueError, TypeError) as e:
|
||||
return {"ok": False, "error": f"Cannot convert parameter '{name}': {e}"}
|
||||
|
||||
# Pass 2: coerce remaining params. Entity instance IDs are resolved from the opened
|
||||
# library file (if any), since you are always appending from another file, never
|
||||
# from the current model.
|
||||
lookup_file = opened_files[0] if opened_files else None
|
||||
for name, value_str in raw_kwargs.items():
|
||||
if name in coerced_kwargs:
|
||||
continue
|
||||
if name not in sig.parameters:
|
||||
return {"ok": False, "error": f"Unknown parameter '{name}' for {module}.{function}"}
|
||||
hint = hints.get(name)
|
||||
try:
|
||||
coerced_kwargs[name] = coerce_value(value_str, hint, model, lookup_file=lookup_file)
|
||||
except (ValueError, TypeError) as e:
|
||||
return {"ok": False, "error": f"Cannot convert parameter '{name}': {e}"}
|
||||
|
||||
|
||||
@@ -15,7 +15,10 @@ classifiers = [
|
||||
"Programming Language :: Python :: 3",
|
||||
"License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)",
|
||||
]
|
||||
dependencies = ["ifcopenshell"]
|
||||
dependencies = ["ifcopenshell", "ifc5d"]
|
||||
|
||||
[project.scripts]
|
||||
ifcedit = "ifcedit.__main__:main"
|
||||
|
||||
[project.urls]
|
||||
Homepage = "http://ifcopenshell.org"
|
||||
|
||||
@@ -8,6 +8,7 @@ import ifcopenshell.api.root
|
||||
import ifcopenshell.api.spatial
|
||||
import ifcopenshell.api.unit
|
||||
import pytest
|
||||
import ifcopenshell.api.material
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -40,3 +41,23 @@ def model_file(model, tmp_path):
|
||||
path = tmp_path / "test.ifc"
|
||||
model.write(str(path))
|
||||
return str(path)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def library():
|
||||
"""Create an IFC4 library with a single IfcWallType asset."""
|
||||
lib = ifcopenshell.api.project.create_file()
|
||||
ifcopenshell.api.owner.settings.get_user = lambda ifc: (ifc.by_type("IfcPersonAndOrganization") or [None])[0]
|
||||
ifcopenshell.api.owner.settings.get_application = lambda ifc: (ifc.by_type("IfcApplication") or [None])[0]
|
||||
ifcopenshell.api.root.create_entity(lib, ifc_class="IfcProject", name="TestLibrary")
|
||||
ifcopenshell.api.unit.assign_unit(lib)
|
||||
ifcopenshell.api.root.create_entity(lib, ifc_class="IfcWallType", name="WAL01")
|
||||
return lib
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def library_file(library, tmp_path):
|
||||
"""Write the library fixture to a temp file and return the path."""
|
||||
path = tmp_path / "library.ifc"
|
||||
library.write(str(path))
|
||||
return str(path)
|
||||
|
||||
@@ -3,6 +3,7 @@ import json
|
||||
from typing import Literal, Optional, Union
|
||||
|
||||
import ifcopenshell
|
||||
import ifcopenshell.api.project
|
||||
import pytest
|
||||
|
||||
from ifcedit.coerce import coerce_value
|
||||
@@ -125,6 +126,20 @@ class TestEntityCoercion:
|
||||
coerce_value("42", ifcopenshell.entity_instance, None)
|
||||
|
||||
|
||||
class TestFileCoercion:
|
||||
def test_opens_file_from_path(self, model_file):
|
||||
result = coerce_value(model_file, ifcopenshell.file)
|
||||
assert isinstance(result, ifcopenshell.file)
|
||||
|
||||
def test_entity_from_lookup_file(self, model_file):
|
||||
lib = ifcopenshell.open(model_file)
|
||||
wall = lib.by_type("IfcWall")[0]
|
||||
empty_model = ifcopenshell.api.project.create_file()
|
||||
result = coerce_value(str(wall.id()), ifcopenshell.entity_instance, empty_model, lookup_file=lib)
|
||||
assert result.id() == wall.id()
|
||||
assert result.is_a("IfcWall")
|
||||
|
||||
|
||||
class TestFallback:
|
||||
def test_no_type_hint(self):
|
||||
assert coerce_value("hello", None) == "hello"
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
from __future__ import annotations
|
||||
|
||||
import ifcopenshell
|
||||
import ifcopenshell.api.aggregate
|
||||
import ifcopenshell.api.owner.settings
|
||||
import ifcopenshell.api.project
|
||||
import ifcopenshell.api.root
|
||||
import ifcopenshell.api.spatial
|
||||
import ifcopenshell.api.unit
|
||||
import pytest
|
||||
|
||||
from ifcedit.quantify import AVAILABLE_RULES, list_rules, run_quantify
|
||||
|
||||
|
||||
class TestListRules:
|
||||
def test_returns_list(self):
|
||||
result = list_rules()
|
||||
assert isinstance(result, list)
|
||||
|
||||
def test_each_entry_has_name(self):
|
||||
result = list_rules()
|
||||
for entry in result:
|
||||
assert "name" in entry
|
||||
|
||||
def test_ifc4_rule_present(self):
|
||||
result = list_rules()
|
||||
names = [r["name"] for r in result]
|
||||
assert "IFC4QtoBaseQuantities" in names
|
||||
|
||||
def test_ifc4x3_rule_present(self):
|
||||
result = list_rules()
|
||||
names = [r["name"] for r in result]
|
||||
assert "IFC4X3QtoBaseQuantities" in names
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def quantify_model():
|
||||
"""Create an IFC4 model with a wall element."""
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
ifcopenshell.api.owner.settings.get_user = lambda ifc: (ifc.by_type("IfcPersonAndOrganization") or [None])[0]
|
||||
ifcopenshell.api.owner.settings.get_application = lambda ifc: (ifc.by_type("IfcApplication") or [None])[0]
|
||||
|
||||
project = ifcopenshell.api.root.create_entity(f, ifc_class="IfcProject", name="TestProject")
|
||||
ifcopenshell.api.unit.assign_unit(f)
|
||||
|
||||
site = ifcopenshell.api.root.create_entity(f, ifc_class="IfcSite", name="TestSite")
|
||||
building = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuilding", name="TestBuilding")
|
||||
storey = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuildingStorey", name="Ground Floor")
|
||||
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[site], relating_object=project)
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[building], relating_object=site)
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[storey], relating_object=building)
|
||||
|
||||
wall = ifcopenshell.api.root.create_entity(f, ifc_class="IfcWall", name="Wall001")
|
||||
ifcopenshell.api.spatial.assign_container(f, products=[wall], relating_structure=storey)
|
||||
|
||||
return f
|
||||
|
||||
|
||||
class TestRunQuantify:
|
||||
def test_returns_ok_true(self, quantify_model):
|
||||
result = run_quantify(quantify_model, "IFC4QtoBaseQuantities")
|
||||
assert result["ok"] is True
|
||||
|
||||
def test_returns_rule_name(self, quantify_model):
|
||||
result = run_quantify(quantify_model, "IFC4QtoBaseQuantities")
|
||||
assert result["rule"] == "IFC4QtoBaseQuantities"
|
||||
|
||||
def test_returns_elements_quantified(self, quantify_model):
|
||||
result = run_quantify(quantify_model, "IFC4QtoBaseQuantities")
|
||||
assert "elements_quantified" in result
|
||||
assert isinstance(result["elements_quantified"], int)
|
||||
|
||||
def test_unknown_rule_returns_error(self, quantify_model):
|
||||
result = run_quantify(quantify_model, "NonExistentRule")
|
||||
assert result["ok"] is False
|
||||
assert "error" in result
|
||||
|
||||
def test_selector_restricts_elements(self, quantify_model):
|
||||
result = run_quantify(quantify_model, "IFC4QtoBaseQuantities", selector="IfcWall")
|
||||
assert result["ok"] is True
|
||||
assert result["rule"] == "IFC4QtoBaseQuantities"
|
||||
|
||||
def test_empty_selector_runs_on_all(self, quantify_model):
|
||||
result = run_quantify(quantify_model, "IFC4QtoBaseQuantities", selector=None)
|
||||
assert result["ok"] is True
|
||||
@@ -1,5 +1,7 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
import ifcopenshell
|
||||
import ifcopenshell.api.pset
|
||||
import ifcopenshell.api.project
|
||||
import ifcopenshell.api.root
|
||||
|
||||
from ifcedit.run import run_api, serialize_result
|
||||
@@ -52,6 +54,21 @@ class TestRunApi:
|
||||
assert "not found" in result["error"]
|
||||
|
||||
|
||||
class TestAppendAsset:
|
||||
def test_append_asset_from_library(self, model, library_file):
|
||||
lib = ifcopenshell.open(library_file)
|
||||
wall_type = lib.by_type("IfcWallType")[0]
|
||||
result = run_api(
|
||||
model,
|
||||
"project",
|
||||
"append_asset",
|
||||
{"library": library_file, "element": str(wall_type.id())},
|
||||
)
|
||||
assert result["ok"] is True
|
||||
assert result["result"]["type"] == "IfcWallType"
|
||||
assert model.by_type("IfcWallType"), "wall type should have been appended to the model"
|
||||
|
||||
|
||||
class TestSerializeResult:
|
||||
def test_none(self):
|
||||
assert serialize_result(None) is None
|
||||
|
||||
+76
-4
@@ -157,6 +157,74 @@ Parameters:
|
||||
- `tolerance` -- intersection tolerance in meters (default: 0.002)
|
||||
- `scope` -- `"storey"` or `"all"` (default: `"storey"`)
|
||||
|
||||
#### ifc_validate
|
||||
|
||||
Check the model for schema and constraint violations.
|
||||
|
||||
```
|
||||
ifc_validate()
|
||||
ifc_validate(express_rules=True)
|
||||
```
|
||||
|
||||
Returns `{"valid": true, "issues": []}` or `{"valid": false, "issues": [{"level": "ERROR", "message": "..."}]}`.
|
||||
|
||||
#### ifc_schedule
|
||||
|
||||
List all work schedules and their nested task trees.
|
||||
|
||||
```
|
||||
ifc_schedule()
|
||||
ifc_schedule(max_depth=1) # top-level phases only
|
||||
```
|
||||
|
||||
`max_depth` limits subtask expansion. At the cutoff, `subtasks` is replaced
|
||||
with `{"truncated": true, "count": N}` so you know children exist without
|
||||
fetching them all. Omit for unlimited depth.
|
||||
|
||||
#### ifc_cost
|
||||
|
||||
List all cost schedules and their nested cost item trees.
|
||||
|
||||
```
|
||||
ifc_cost()
|
||||
ifc_cost(max_depth=2) # top two levels of the BoQ
|
||||
```
|
||||
|
||||
`max_depth` limits cost item expansion, same truncation convention as
|
||||
`ifc_schedule`.
|
||||
|
||||
#### ifc_schema
|
||||
|
||||
Return IFC class documentation for any entity type, using the loaded model's
|
||||
schema version.
|
||||
|
||||
```
|
||||
ifc_schema(entity_type="IfcWall")
|
||||
ifc_schema(entity_type="IfcBuildingStorey")
|
||||
```
|
||||
|
||||
Returns description, predefined types, spec URL, and attribute descriptions.
|
||||
Returns `{"error": "Unknown entity: Foo"}` for unrecognised types.
|
||||
|
||||
#### ifc_quantify
|
||||
|
||||
Run quantity take-off (QTO) on the loaded model using an `ifc5d` rule.
|
||||
Computes physical measurements (volume, area, length, count, weight) and
|
||||
writes them back as `IfcElementQuantity` property sets. Modifies the model
|
||||
in-place -- call `ifc_save()` when done.
|
||||
|
||||
```
|
||||
ifc_quantify(rule="IFC4QtoBaseQuantities")
|
||||
ifc_quantify(rule="IFC4QtoBaseQuantities", selector="IfcWall")
|
||||
```
|
||||
|
||||
Available rules: `IFC4QtoBaseQuantities`, `IFC4X3QtoBaseQuantities`.
|
||||
|
||||
`selector` is an optional ifcopenshell selector to restrict which elements
|
||||
are quantified (default: all `IfcElement`).
|
||||
|
||||
Returns `{"ok": true, "rule": "...", "elements_quantified": 42}`.
|
||||
|
||||
### Edit discovery tools
|
||||
|
||||
#### ifc_list
|
||||
@@ -209,10 +277,14 @@ Does NOT auto-save -- call `ifc_save()` when ready to write changes to disk.
|
||||
|
||||
1. **Load** a model: `ifc_load`
|
||||
2. **Inspect** with query tools: `ifc_summary`, `ifc_tree`, `ifc_select`, `ifc_info`, `ifc_relations`
|
||||
3. **Find** the right API function: `ifc_list`, `ifc_docs`
|
||||
4. **Edit** the model: `ifc_edit`
|
||||
5. **Verify** changes with query tools
|
||||
6. **Save** when satisfied: `ifc_save`
|
||||
3. **Validate** if needed: `ifc_validate`
|
||||
4. **Browse schedules / costs**: `ifc_schedule`, `ifc_cost` (use `max_depth=1` first on large projects)
|
||||
5. **Look up IFC classes**: `ifc_schema`
|
||||
6. **Find** the right API function: `ifc_list`, `ifc_docs`
|
||||
7. **Edit** the model: `ifc_edit`
|
||||
8. **Quantify** elements: `ifc_quantify` (writes QTO psets in-place)
|
||||
9. **Verify** changes with query tools
|
||||
10. **Save** when satisfied: `ifc_save`
|
||||
|
||||
The model stays in memory across all calls, so multi-step editing sessions
|
||||
are fast -- no file I/O between operations.
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
# ifc_cli/src/ifcmcp/ifcmcp/__main__.py
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
from ifcmcp.server import build_server
|
||||
|
||||
server = build_server()
|
||||
server.run(transport="stdio")
|
||||
def main():
|
||||
server = build_server()
|
||||
server.run(transport="stdio")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+146
-2
@@ -1,4 +1,4 @@
|
||||
# ifc_cli/src/ifcmcp/ifcmcp/core.py
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
@@ -8,9 +8,12 @@ from typing import Any, Callable
|
||||
import ifcopenshell
|
||||
|
||||
from ifcedit.discover import function_docs, list_functions, list_modules
|
||||
from ifcedit.quantify import run_quantify
|
||||
from ifcedit.run import run_api
|
||||
from ifcquery import clash as clash_mod
|
||||
from ifcquery import info, relations, select, summary, tree
|
||||
from ifcquery import cost as cost_mod
|
||||
from ifcquery import info, relations, render as render_mod, schedule, schema, select, summary, tree
|
||||
from ifcquery import validate as validate_mod
|
||||
|
||||
|
||||
# inside ifcmcp/core.py
|
||||
@@ -181,6 +184,65 @@ class IfcSession:
|
||||
res = run_api(model, module, function, raw_kwargs)
|
||||
return _jsonify(res)
|
||||
|
||||
# ------------------------
|
||||
# Extended query + edit tools
|
||||
# ------------------------
|
||||
def ifc_validate(self, express_rules: bool = False) -> dict[str, Any]:
|
||||
"""Validate the loaded model. Returns {'valid': bool, 'issues': [...]}."""
|
||||
return validate_mod.validate(self._require_model(), express_rules=express_rules)
|
||||
|
||||
def ifc_schedule(self, max_depth: int | None = None) -> list[dict[str, Any]]:
|
||||
"""List work schedules and nested tasks from the model.
|
||||
|
||||
max_depth limits subtask expansion (None = unlimited). At the cutoff,
|
||||
subtasks is replaced with {"truncated": True, "count": N}.
|
||||
"""
|
||||
return schedule.schedule(self._require_model(), max_depth=max_depth)
|
||||
|
||||
def ifc_cost(self, max_depth: int | None = None) -> list[dict[str, Any]]:
|
||||
"""List cost schedules and nested cost items from the model.
|
||||
|
||||
max_depth limits cost item expansion (None = unlimited). At the cutoff,
|
||||
subitems is replaced with {"truncated": True, "count": N}.
|
||||
"""
|
||||
return cost_mod.cost(self._require_model(), max_depth=max_depth)
|
||||
|
||||
def ifc_schema(self, entity_type: str) -> dict[str, Any]:
|
||||
"""Return IFC class documentation for entity_type using the model's schema version."""
|
||||
return schema.schema(self._require_model(), entity_type)
|
||||
|
||||
def ifc_render(
|
||||
self,
|
||||
selector: str = "",
|
||||
element_ids: list[int] | None = None,
|
||||
view: str = "iso",
|
||||
) -> bytes:
|
||||
"""Render the loaded model to a PNG image and return raw bytes.
|
||||
|
||||
:param selector: ifcopenshell selector to restrict rendered elements
|
||||
(e.g. ``'IfcWall'``). Omit to render the whole model.
|
||||
:param element_ids: Step IDs of elements to highlight. Other elements
|
||||
are rendered in translucent grey.
|
||||
:param view: Camera angle: ``iso``, ``top``, ``south``, ``north``,
|
||||
``east``, or ``west``.
|
||||
:return: PNG image as raw bytes.
|
||||
"""
|
||||
model = self._require_model()
|
||||
return render_mod.render(
|
||||
model,
|
||||
selector=selector if selector else None,
|
||||
element_ids=element_ids,
|
||||
view=view,
|
||||
)
|
||||
|
||||
def ifc_quantify(self, rule: str, selector: str = "") -> dict[str, Any]:
|
||||
"""Run quantity take-off on the model using the named rule.
|
||||
|
||||
Modifies the model in-place; call ifc_save() after.
|
||||
"""
|
||||
model = self._require_model()
|
||||
return run_quantify(model, rule, selector=selector if selector else None)
|
||||
|
||||
# ------------------------
|
||||
# Generic dispatcher + tool specs for LLMs
|
||||
# ------------------------
|
||||
@@ -300,4 +362,86 @@ class IfcSession:
|
||||
"additionalProperties": False,
|
||||
},
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"name": "ifc_validate",
|
||||
"description": "Validate the loaded model. Returns valid bool and list of issues.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"express_rules": {"type": "boolean", "description": "Also check EXPRESS rules (slower)"}},
|
||||
"required": [],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"name": "ifc_schedule",
|
||||
"description": "List work schedules and nested tasks. Use max_depth=1 for top-level phases only on large projects.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"max_depth": {"type": "integer", "description": "Max levels of subtask expansion (omit for unlimited)"}},
|
||||
"required": [],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"name": "ifc_cost",
|
||||
"description": "List cost schedules and nested cost items. Use max_depth=1 for top-level sections only on large BoQs.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"max_depth": {"type": "integer", "description": "Max levels of cost item expansion (omit for unlimited)"}},
|
||||
"required": [],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"name": "ifc_schema",
|
||||
"description": "Return IFC class documentation for an entity type.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {"entity_type": {"type": "string", "description": "IFC entity type, e.g. IfcWall"}},
|
||||
"required": ["entity_type"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"name": "ifc_quantify",
|
||||
"description": "Run quantity take-off (QTO) on the model. Modifies model in-place; call ifc_save() after.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"rule": {"type": "string", "description": "QTO rule name, e.g. IFC4QtoBaseQuantities"},
|
||||
"selector": {"type": "string", "description": "ifcopenshell selector to restrict elements (default: all IfcElement)"},
|
||||
},
|
||||
"required": ["rule"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"name": "ifc_render",
|
||||
"description": (
|
||||
"Render the loaded IFC model to a PNG image for visual inspection. "
|
||||
"Use selector to restrict which elements are rendered (e.g. a single storey). "
|
||||
"Use element_ids to highlight elements against a greyed-out background. "
|
||||
"Returns base64-encoded PNG bytes."
|
||||
),
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"selector": {"type": "string", "description": "ifcopenshell selector (default: whole model)"},
|
||||
"element_ids": {"type": "array", "items": {"type": "integer"}, "description": "Step IDs of elements to highlight"},
|
||||
"view": {
|
||||
"type": "string",
|
||||
"enum": ["iso", "top", "south", "north", "east", "west"],
|
||||
"description": "Camera angle (default: iso)",
|
||||
},
|
||||
},
|
||||
"required": [],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
},
|
||||
]
|
||||
@@ -1,4 +1,4 @@
|
||||
# ifc_cli/src/ifcmcp/ifcmcp/embedded.py
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Mapping
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
# ifc_cli/src/ifcmcp/ifcmcp/server.py
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from typing import Any
|
||||
|
||||
from ifcmcp.core import IfcSession
|
||||
|
||||
try:
|
||||
from mcp.server.fastmcp import FastMCP # type: ignore
|
||||
from mcp.types import ImageContent # type: ignore
|
||||
except Exception: # pragma: no cover
|
||||
FastMCP = None # type: ignore
|
||||
ImageContent = None # type: ignore
|
||||
|
||||
|
||||
def build_server() -> Any:
|
||||
@@ -95,4 +98,47 @@ def build_server() -> Any:
|
||||
def ifc_edit(function_path: str, params: str = "{}") -> dict:
|
||||
return session.ifc_edit(function_path=function_path, params=params)
|
||||
|
||||
# ---- Extended query + edit ----
|
||||
@server.tool()
|
||||
def ifc_validate(express_rules: bool = False) -> dict[str, Any]:
|
||||
return session.ifc_validate(express_rules=express_rules)
|
||||
|
||||
@server.tool()
|
||||
def ifc_schedule(max_depth: int | None = None) -> list[dict[str, Any]]:
|
||||
return session.ifc_schedule(max_depth=max_depth)
|
||||
|
||||
@server.tool()
|
||||
def ifc_cost(max_depth: int | None = None) -> list[dict[str, Any]]:
|
||||
return session.ifc_cost(max_depth=max_depth)
|
||||
|
||||
@server.tool()
|
||||
def ifc_schema(entity_type: str) -> dict[str, Any]:
|
||||
return session.ifc_schema(entity_type=entity_type)
|
||||
|
||||
@server.tool()
|
||||
def ifc_quantify(rule: str, selector: str = "") -> dict[str, Any]:
|
||||
return session.ifc_quantify(rule=rule, selector=selector)
|
||||
|
||||
@server.tool(structured_output=False)
|
||||
def ifc_render(
|
||||
selector: str = "",
|
||||
element_ids: list[int] | None = None,
|
||||
view: str = "iso",
|
||||
) -> list[ImageContent]:
|
||||
"""Render the loaded IFC model to a PNG image.
|
||||
|
||||
Returns an inline image the LLM can inspect to understand the spatial
|
||||
layout of the model or a specific element in context.
|
||||
|
||||
:param selector: ifcopenshell selector to restrict rendered elements
|
||||
(e.g. ``'IfcWall'``, ``'IfcBuildingStorey[Name="0"]'``).
|
||||
Omit to render the whole model.
|
||||
:param element_ids: Step IDs of elements to highlight. Other elements
|
||||
are rendered in translucent grey so the subject stands out.
|
||||
:param view: Camera angle — ``iso`` (default), ``top``, ``south``,
|
||||
``north``, ``east``, or ``west``.
|
||||
"""
|
||||
png_bytes = session.ifc_render(selector=selector, element_ids=element_ids, view=view)
|
||||
return [ImageContent(type="image", data=base64.b64encode(png_bytes).decode(), mimeType="image/png")]
|
||||
|
||||
return server
|
||||
@@ -19,6 +19,9 @@ dependencies = ["ifcopenshell", "ifcquery", "ifcedit"]
|
||||
[project.optional-dependencies]
|
||||
mcp = ["mcp"]
|
||||
|
||||
[project.scripts]
|
||||
ifcmcp = "ifcmcp.__main__:main"
|
||||
|
||||
[project.urls]
|
||||
Homepage = "http://ifcopenshell.org"
|
||||
Documentation = "https://docs.ifcopenshell.org"
|
||||
|
||||
@@ -197,6 +197,133 @@ ifcquery model.ifc relations 10 --traverse up
|
||||
]
|
||||
```
|
||||
|
||||
### validate
|
||||
|
||||
Check the model for schema and constraint violations.
|
||||
|
||||
```bash
|
||||
ifcquery model.ifc validate
|
||||
ifcquery model.ifc validate --rules
|
||||
```
|
||||
|
||||
Options:
|
||||
|
||||
- `--rules` -- also run the slower EXPRESS rules check (default: off)
|
||||
|
||||
```json
|
||||
{
|
||||
"valid": true,
|
||||
"issues": []
|
||||
}
|
||||
```
|
||||
|
||||
On an invalid model:
|
||||
|
||||
```json
|
||||
{
|
||||
"valid": false,
|
||||
"issues": [
|
||||
{"level": "ERROR", "message": "Entity #42 IfcWall.GlobalId is not a valid IfcGloballyUniqueId"}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### schedule
|
||||
|
||||
List all work schedules and their task trees from the model.
|
||||
|
||||
```bash
|
||||
ifcquery model.ifc schedule
|
||||
ifcquery model.ifc schedule --depth 1
|
||||
```
|
||||
|
||||
Options:
|
||||
|
||||
- `--depth N` -- expand at most N levels of subtasks (default: unlimited). At the
|
||||
cutoff, `subtasks` is replaced with `{"truncated": true, "count": N}`.
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"id": 42,
|
||||
"name": "Construction Schedule",
|
||||
"predefined_type": "BASELINE",
|
||||
"tasks": [
|
||||
{
|
||||
"id": 55,
|
||||
"name": "Phase 1",
|
||||
"start": "2024-01-01T09:00:00",
|
||||
"finish": "2024-06-30T17:00:00",
|
||||
"is_milestone": false,
|
||||
"outputs": [{"id": 10, "type": "IfcWall", "name": "Wall A"}],
|
||||
"subtasks": [
|
||||
{"id": 56, "name": "Foundations", "start": null, "finish": null,
|
||||
"is_milestone": false, "outputs": [], "subtasks": []}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
### cost
|
||||
|
||||
List all cost schedules and their cost item trees from the model.
|
||||
|
||||
```bash
|
||||
ifcquery model.ifc cost
|
||||
ifcquery model.ifc cost --depth 2
|
||||
```
|
||||
|
||||
Options:
|
||||
|
||||
- `--depth N` -- expand at most N levels of subitems (default: unlimited). At the
|
||||
cutoff, `subitems` is replaced with `{"truncated": true, "count": N}`.
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"id": 100,
|
||||
"name": "Bill of Quantities",
|
||||
"predefined_type": "COSTPLAN",
|
||||
"items": [
|
||||
{
|
||||
"id": 110,
|
||||
"name": "Concrete Works",
|
||||
"values": [{"formula": "1200.00 = material(1200.0)", "category": "material"}],
|
||||
"subitems": [
|
||||
{"id": 111, "name": "Formwork", "values": [], "subitems": []}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
### schema
|
||||
|
||||
Show IFC class documentation for any entity type, using the schema version of
|
||||
the loaded model.
|
||||
|
||||
```bash
|
||||
ifcquery model.ifc schema IfcWall
|
||||
ifcquery model.ifc schema IfcBuildingStorey
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"description": "The wall represents a vertical construction ...",
|
||||
"predefined_types": {"STANDARD": "A standard wall, extruded vertically ..."},
|
||||
"spec_url": "https://standards.buildingsmart.org/...",
|
||||
"attributes": {
|
||||
"Name": "Optional name for use by the participating software systems",
|
||||
"ObjectPlacement": "Placement of the product in space ..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Returns `{"error": "Unknown entity: Foo"}` for unrecognised types.
|
||||
|
||||
### clash
|
||||
|
||||
Check a single element for geometric intersections and clearance violations
|
||||
|
||||
@@ -21,12 +21,15 @@ from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
import ifcopenshell
|
||||
|
||||
from ifcquery import clash as clash_mod
|
||||
from ifcquery import info, relations, select, summary, tree
|
||||
from ifcquery import cost as cost_mod
|
||||
from ifcquery import info, relations, render as render_mod, schedule, schema, select, summary, tree, plot
|
||||
from ifcquery import validate as validate_mod
|
||||
|
||||
|
||||
def parse_element_id(raw: str) -> int:
|
||||
@@ -103,6 +106,88 @@ def main():
|
||||
"--scope", choices=["storey", "all"], default="storey", help="Scope of elements to check (default: storey)"
|
||||
)
|
||||
|
||||
validate_parser = subparsers.add_parser("validate", help="Schema/constraint validation")
|
||||
validate_parser.add_argument(
|
||||
"--rules", action="store_true", help="Also check EXPRESS rules (slower, default: false)"
|
||||
)
|
||||
|
||||
schedule_parser = subparsers.add_parser("schedule", help="List work plans and tasks from the model")
|
||||
schedule_parser.add_argument(
|
||||
"--depth", type=int, default=None, metavar="N", help="Limit subtask expansion to N levels (default: unlimited)"
|
||||
)
|
||||
|
||||
cost_parser = subparsers.add_parser("cost", help="List cost schedules and cost items from the model")
|
||||
cost_parser.add_argument(
|
||||
"--depth", type=int, default=None, metavar="N", help="Limit cost item expansion to N levels (default: unlimited)"
|
||||
)
|
||||
|
||||
schema_parser = subparsers.add_parser("schema", help="IFC class documentation")
|
||||
schema_parser.add_argument("entity_type", help="IFC entity type (e.g. IfcWall)")
|
||||
|
||||
render_parser = subparsers.add_parser("render", help="Render model geometry to a PNG image")
|
||||
render_parser.add_argument(
|
||||
"-o", "--output", default="", metavar="FILE", help="Output PNG path (default: <ifc_file>.png)"
|
||||
)
|
||||
render_parser.add_argument(
|
||||
"--selector", default="", metavar="QUERY", help="ifcopenshell selector to restrict rendered elements"
|
||||
)
|
||||
render_parser.add_argument(
|
||||
"--element", default="", metavar="ID[,ID...]",
|
||||
help="Comma-separated step IDs of elements to highlight (rest rendered in grey)"
|
||||
)
|
||||
render_parser.add_argument(
|
||||
"--view",
|
||||
choices=render_mod.VIEWS,
|
||||
default="iso",
|
||||
help="Camera angle (default: iso)",
|
||||
)
|
||||
|
||||
plot_parser = subparsers.add_parser("plot", help="Plot model drawing (SVG via ifcopenshell.draw; optional PNG via CairoSVG)")
|
||||
plot_parser.add_argument(
|
||||
"-o", "--output", default="", metavar="FILE",
|
||||
help="Output file path. Default depends on --out-format: <ifc_file>.svg/.png"
|
||||
)
|
||||
plot_parser.add_argument(
|
||||
"--out-format",
|
||||
choices=["svg", "png", "base64"],
|
||||
default="png",
|
||||
help="Output format: svg (write SVG), png (write PNG), base64 (print base64 in JSON/text). Default: png",
|
||||
)
|
||||
plot_parser.add_argument(
|
||||
"--selector", default="", metavar="QUERY",
|
||||
help="ifcopenshell selector to restrict plotted elements"
|
||||
)
|
||||
plot_parser.add_argument(
|
||||
"--element", default="", metavar="ID[,ID...]",
|
||||
help="Comma-separated step IDs of elements to highlight"
|
||||
)
|
||||
plot_parser.add_argument(
|
||||
"--view",
|
||||
choices=getattr(plot, "VIEWS", ("floorplan", "elevation", "section", "auto")),
|
||||
default="floorplan",
|
||||
help="Drawing view (default: floorplan)",
|
||||
)
|
||||
plot_parser.add_argument(
|
||||
"--width-mm", type=float, default=297.0, metavar="MM",
|
||||
help="Paper width in mm (default: 297)",
|
||||
)
|
||||
plot_parser.add_argument(
|
||||
"--height-mm", type=float, default=420.0, metavar="MM",
|
||||
help="Paper height in mm (default: 420)",
|
||||
)
|
||||
plot_parser.add_argument(
|
||||
"--scale", type=float, default=1.0 / 100.0, metavar="S",
|
||||
help="Model-to-paper scale (default: 0.01 = 1:100)",
|
||||
)
|
||||
plot_parser.add_argument(
|
||||
"--png-width", type=int, default=1024, metavar="PX",
|
||||
help="PNG width in pixels (default: 1024)",
|
||||
)
|
||||
plot_parser.add_argument(
|
||||
"--png-height", type=int, default=1024, metavar="PX",
|
||||
help="PNG height in pixels (default: 1024)",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
@@ -159,6 +244,74 @@ def main():
|
||||
except ImportError:
|
||||
print("Error: ifcopenshell geometry engine not available (C++ bindings required)", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
elif args.command == "validate":
|
||||
result = validate_mod.validate(model, express_rules=args.rules)
|
||||
elif args.command == "schedule":
|
||||
result = schedule.schedule(model, max_depth=args.depth)
|
||||
elif args.command == "cost":
|
||||
result = cost_mod.cost(model, max_depth=args.depth)
|
||||
elif args.command == "schema":
|
||||
result = schema.schema(model, args.entity_type)
|
||||
elif args.command == "render":
|
||||
element_ids = None
|
||||
if args.element:
|
||||
try:
|
||||
element_ids = [parse_element_id(part) for part in args.element.split(",")]
|
||||
except ValueError:
|
||||
print(f"Error: Invalid element ID(s): {args.element}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
out_path = args.output or (os.path.splitext(args.ifc_file)[0] + ".png")
|
||||
try:
|
||||
png_bytes = render_mod.render(
|
||||
model,
|
||||
selector=args.selector or None,
|
||||
element_ids=element_ids,
|
||||
view=args.view,
|
||||
)
|
||||
except ImportError as e:
|
||||
print(f"Error: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
except ValueError as e:
|
||||
print(f"Error: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
with open(out_path, "wb") as f:
|
||||
f.write(png_bytes)
|
||||
print(f"Saved render to {out_path}", file=sys.stderr)
|
||||
return
|
||||
elif args.command == "plot":
|
||||
element_ids = None
|
||||
if args.element:
|
||||
try:
|
||||
element_ids = [parse_element_id(part) for part in args.element.split(",")]
|
||||
except ValueError:
|
||||
print(f"Error: Invalid element ID(s): {args.element}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
# Choose default output extension based on out-format
|
||||
base = os.path.splitext(args.ifc_file)[0]
|
||||
if args.out_format == "svg":
|
||||
out_path = args.output or (base + ".svg")
|
||||
elif args.out_format == "png":
|
||||
out_path = args.output or (base + ".png")
|
||||
else:
|
||||
out_path = args.output # unused; base64 prints to stdout via format_output
|
||||
|
||||
png_bytes = plot.plot(
|
||||
model,
|
||||
selector=args.selector or None,
|
||||
element_ids=element_ids,
|
||||
view=args.view,
|
||||
width_mm=args.width_mm,
|
||||
height_mm=args.height_mm,
|
||||
scale=args.scale,
|
||||
output_format=args.out_format
|
||||
)
|
||||
with open(out_path, "wb") as f:
|
||||
f.write(png_bytes)
|
||||
|
||||
print(f"Saved render to {out_path}", file=sys.stderr)
|
||||
return
|
||||
|
||||
|
||||
print(format_output(result, args.output_format))
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import ifcopenshell
|
||||
import ifcopenshell.util.cost as cost_util
|
||||
|
||||
|
||||
def _cost_item_to_dict(item: ifcopenshell.entity_instance, max_depth: int | None, depth: int) -> dict[str, Any]:
|
||||
raw_values = cost_util.get_cost_values(item)
|
||||
values = [{"formula": v.get("label", ""), "category": v.get("category")} for v in raw_values]
|
||||
|
||||
if max_depth is not None and depth >= max_depth:
|
||||
child_count = len(cost_util.get_nested_cost_items(item))
|
||||
subitems = {"truncated": True, "count": child_count} if child_count else []
|
||||
else:
|
||||
subitems = [_cost_item_to_dict(sub, max_depth, depth + 1) for sub in cost_util.get_nested_cost_items(item)]
|
||||
|
||||
return {
|
||||
"id": item.id(),
|
||||
"name": getattr(item, "Name", None),
|
||||
"values": values,
|
||||
"subitems": subitems,
|
||||
}
|
||||
|
||||
|
||||
def cost(model: ifcopenshell.file, max_depth: int | None = None) -> list[dict[str, Any]]:
|
||||
"""Return a list of IfcCostSchedule entries with nested cost item trees.
|
||||
|
||||
max_depth limits how many levels of subitems are expanded (None = unlimited).
|
||||
At the cutoff level, subitems is replaced with {"truncated": True, "count": N}.
|
||||
"""
|
||||
result = []
|
||||
for cost_schedule in model.by_type("IfcCostSchedule"):
|
||||
items = [_cost_item_to_dict(i, max_depth, depth=1) for i in cost_util.get_root_cost_items(cost_schedule)]
|
||||
result.append(
|
||||
{
|
||||
"id": cost_schedule.id(),
|
||||
"name": getattr(cost_schedule, "Name", None),
|
||||
"predefined_type": getattr(cost_schedule, "PredefinedType", None),
|
||||
"items": items,
|
||||
}
|
||||
)
|
||||
return result
|
||||
@@ -0,0 +1,238 @@
|
||||
# IfcQuery - IFC model interrogation CLI
|
||||
# Copyright (C) 2026 Bruno Postle <bruno@postle.net>
|
||||
#
|
||||
# This file is part of IfcQuery.
|
||||
#
|
||||
# IfcQuery is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# IfcQuery 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 Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with IfcQuery. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
import ifcopenshell
|
||||
import ifcopenshell.geom
|
||||
import ifcopenshell.util.selector
|
||||
import ifcopenshell.draw
|
||||
|
||||
from xml.etree.ElementTree import ElementTree, Element, SubElement, register_namespace
|
||||
|
||||
try:
|
||||
import cairosvg # type: ignore
|
||||
|
||||
_HAS_CAIROSVG = True
|
||||
except Exception:
|
||||
_HAS_CAIROSVG = False
|
||||
|
||||
|
||||
try:
|
||||
from PIL import Image # type: ignore
|
||||
|
||||
_HAS_PIL = True
|
||||
except Exception:
|
||||
_HAS_PIL = False
|
||||
|
||||
VIEWS = ("floorplan", "elevation", "section", "auto")
|
||||
OUTPUT_FORMATS = ("svg", "png", "base64")
|
||||
|
||||
|
||||
def _escape_css_attr(name: str) -> str:
|
||||
# CSS attribute selectors must escape ':' (e.g. ifc:guid -> ifc\:guid)
|
||||
return name.replace(":", "\\:")
|
||||
|
||||
|
||||
def _highlight_css_from_ids(model: ifcopenshell.file, element_ids: list[int]) -> str:
|
||||
guids: list[str] = []
|
||||
for sid in element_ids:
|
||||
e = model.by_id(int(sid))
|
||||
if e is None:
|
||||
continue
|
||||
gid = getattr(e, "GlobalId", None)
|
||||
if isinstance(gid, str) and gid:
|
||||
guids.append(gid)
|
||||
|
||||
if not guids:
|
||||
return ""
|
||||
|
||||
attr = _escape_css_attr("ifc:guid")
|
||||
|
||||
css = [
|
||||
"/* Auto-highlight injected by ifcquery.plot */",
|
||||
f'[{attr}] path {{ opacity: 0.10; }}',
|
||||
f'[{attr}] text {{ opacity: 0.25; }}',
|
||||
]
|
||||
for gid in guids:
|
||||
css.append(f'[{attr}="{gid}"] path {{ opacity: 1.0; stroke: #d00; stroke-width: 0.25; }}')
|
||||
css.append(f'[{attr}="{gid}"] text {{ opacity: 1.0; fill: #d00; }}')
|
||||
return "\n".join(css) + "\n"
|
||||
|
||||
|
||||
def _make_filtered_iterator(model: ifcopenshell.file, include_elements: list[Any]) -> ifcopenshell.geom.iterator:
|
||||
# Avoid multiprocessing in WASM; os.cpu_count is good enough.
|
||||
n_threads = os.cpu_count() or 1
|
||||
|
||||
# These flags mirror the defaults used by ifcopenshell.draw in v0.8.x.
|
||||
geom_settings = ifcopenshell.geom.settings(
|
||||
REORIENT_SHELLS=False,
|
||||
ELEMENT_HIERARCHY=True,
|
||||
)
|
||||
|
||||
# IfcOpenShell wrapper constants may live in different places across builds.
|
||||
wrapper = getattr(ifcopenshell, "ifcopenshell_wrapper", None)
|
||||
if wrapper is not None:
|
||||
try:
|
||||
geom_settings.set("iterator-output", wrapper.NATIVE)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
geom_settings.set("apply-default-materials", True)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
geom_settings.set("dimensionality", wrapper.SURFACES_AND_SOLIDS)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return ifcopenshell.geom.iterator(geom_settings, model, n_threads, include=include_elements)
|
||||
|
||||
|
||||
def plot(
|
||||
model: ifcopenshell.file,
|
||||
*,
|
||||
output_format: str = "png",
|
||||
selector: str | None = None,
|
||||
element_ids: list[int] | None = None,
|
||||
view: str = "floorplan",
|
||||
# SVG / page sizing (draw works in mm coordinates)
|
||||
width_mm: float = 297.0,
|
||||
height_mm: float = 420.0,
|
||||
scale: float = 1.0 / 100.0,
|
||||
merge_projection: bool = True,
|
||||
# PNG sizing (only for output_format png/base64)
|
||||
png_width: int = 1024,
|
||||
png_height: int = 1024,
|
||||
) -> bytes | dict[str, Any]:
|
||||
"""
|
||||
Plot IFC model as SVG (via ifcopenshell.draw) or PNG/base64 (via CairoSVG).
|
||||
|
||||
Args:
|
||||
model: In-memory IFC model.
|
||||
output_format: 'svg' | 'png' | 'base64'
|
||||
- 'svg' -> returns SVG bytes
|
||||
- 'png' -> returns PNG bytes
|
||||
- 'base64'-> returns dict: {mime, png_b64, width, height, view}
|
||||
selector: ifcopenshell selector query to restrict plotted elements.
|
||||
element_ids: STEP ids to highlight; non-highlighted geometry is faded.
|
||||
view: One of VIEWS ('floorplan', 'elevation', 'section', 'auto').
|
||||
width_mm, height_mm: Page size in mm.
|
||||
scale: Model-to-paper scale (0.01 means 1:100).
|
||||
merge_projection: Passed through to ifcopenshell.draw.main.
|
||||
png_width, png_height: Raster size in pixels for png/base64 outputs.
|
||||
|
||||
Raises:
|
||||
ImportError: if ifcopenshell.draw or CairoSVG is not available (as required).
|
||||
ValueError: invalid args or selector matches nothing.
|
||||
"""
|
||||
if output_format not in OUTPUT_FORMATS:
|
||||
raise ValueError(f"output_format must be one of {OUTPUT_FORMATS}, got {output_format!r}")
|
||||
if view not in VIEWS:
|
||||
raise ValueError(f"view must be one of {VIEWS}, got {view!r}")
|
||||
if not _HAS_DRAW:
|
||||
raise ImportError("ifcopenshell.draw is not available in this environment.")
|
||||
|
||||
# Configure draw settings
|
||||
settings = ifcopenshell.draw.draw_settings(
|
||||
auto_floorplan=(view in ("floorplan", "auto")),
|
||||
auto_elevation=(view in ("elevation", "auto")),
|
||||
auto_section=(view in ("section", "auto")),
|
||||
width=width_mm,
|
||||
height=height_mm,
|
||||
scale=scale,
|
||||
css="",
|
||||
)
|
||||
|
||||
# Optional highlight CSS overlay
|
||||
if element_ids:
|
||||
settings.css = _highlight_css_from_ids(model, element_ids)
|
||||
|
||||
# Optional element restriction via selector -> custom iterator
|
||||
iterators: tuple[Any, ...] = ()
|
||||
if selector:
|
||||
include_elements = list(ifcopenshell.util.selector.filter_elements(model, selector))
|
||||
if not include_elements:
|
||||
raise ValueError(f"Selector {selector!r} matched no elements")
|
||||
it = _make_filtered_iterator(model, include_elements)
|
||||
iterators = (it,)
|
||||
# If we explicitly include elements, don't rely on exclude_entities (best-effort).
|
||||
settings.exclude_entities = ""
|
||||
|
||||
# Generate SVG
|
||||
svg_bytes = ifcopenshell.draw.main(
|
||||
settings,
|
||||
files=[model],
|
||||
iterators=iterators,
|
||||
merge_projection=merge_projection,
|
||||
)
|
||||
|
||||
register_namespace('',"http://www.w3.org/2000/svg")
|
||||
|
||||
def svg_split(f):
|
||||
x = ElementTree(file=f)
|
||||
svg = x.getroot()
|
||||
resources = []
|
||||
for child in svg:
|
||||
if child.tag == "{http://www.w3.org/2000/svg}g":
|
||||
root = Element(svg.tag, svg.attrib)
|
||||
n = ElementTree(root)
|
||||
for r in (resources + [child]):
|
||||
root.append(r)
|
||||
b = BytesIO()
|
||||
n.write(b,
|
||||
xml_declaration = True,
|
||||
encoding = 'utf-8',
|
||||
method = 'xml')
|
||||
yield b.getvalue()
|
||||
else:
|
||||
resources.append(child)
|
||||
|
||||
if output_format == "svg":
|
||||
return svg_bytes
|
||||
|
||||
# Need CairoSVG for png/base64
|
||||
if not _HAS_CAIROSVG:
|
||||
raise ImportError("CairoSVG is not installed. Install with: pip install cairosvg")
|
||||
|
||||
composite = None
|
||||
png_bytes = None
|
||||
svgs = list(svg_split(BytesIO(svg_bytes)))
|
||||
for i, svgb in enumerate(svgs):
|
||||
png_bytes = cairosvg.svg2png(bytestring=svgb, output_width=png_width, output_height=png_height)
|
||||
if len(svgs) == 1:
|
||||
break
|
||||
|
||||
# Need Pillow for concatenating images
|
||||
if not _HAS_PIL:
|
||||
raise ImportError("Pillow is not installed. Install with: pip install Pillow")
|
||||
|
||||
if composite is None:
|
||||
composite = Image.new('RGBA', (png_width, png_height * len(svgs)))
|
||||
img = Image.open(BytesIO(png_bytes))
|
||||
composite.paste(img, (0, png_height * i))
|
||||
if composite is not None:
|
||||
b = BytesIO()
|
||||
composite.save(b, 'png')
|
||||
png_bytes = b.getvalue()
|
||||
|
||||
return png_bytes
|
||||
@@ -0,0 +1,183 @@
|
||||
# IfcQuery - IFC model interrogation CLI
|
||||
# Copyright (C) 2026 Bruno Postle <bruno@postle.net>
|
||||
#
|
||||
# This file is part of IfcQuery.
|
||||
#
|
||||
# IfcQuery is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU Lesser General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# IfcQuery 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 Lesser General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU Lesser General Public License
|
||||
# along with IfcQuery. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import multiprocessing
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
import ifcopenshell
|
||||
import ifcopenshell.geom
|
||||
import ifcopenshell.util.selector
|
||||
|
||||
try:
|
||||
import numpy as np
|
||||
import pyvista as pv
|
||||
|
||||
_HAS_PYVISTA = True
|
||||
except ImportError:
|
||||
_HAS_PYVISTA = False
|
||||
|
||||
VIEWS = ("iso", "top", "south", "north", "east", "west")
|
||||
|
||||
|
||||
def _apply_view(plotter: "pv.Plotter", view: str) -> None:
|
||||
"""Set the camera to the requested named view. Z is up (IFC convention)."""
|
||||
if view == "top":
|
||||
plotter.view_xy()
|
||||
elif view == "south":
|
||||
# Camera at -Y looking toward +Y (south face of building)
|
||||
plotter.view_xz(negative=True)
|
||||
elif view == "north":
|
||||
plotter.view_xz(negative=False)
|
||||
elif view == "east":
|
||||
plotter.view_yz(negative=False)
|
||||
elif view == "west":
|
||||
plotter.view_yz(negative=True)
|
||||
else:
|
||||
plotter.view_isometric()
|
||||
# Ensure Z is world up for elevation views
|
||||
if view not in ("top",):
|
||||
plotter.camera.up = (0, 0, 1)
|
||||
|
||||
|
||||
def _add_shape(
|
||||
shape: object,
|
||||
plotter: "pv.Plotter",
|
||||
highlight_ids: frozenset[int] | None,
|
||||
) -> None:
|
||||
"""Triangulate and add a geometry shape to the plotter."""
|
||||
geom = shape.geometry
|
||||
verts = np.array(geom.verts, dtype=float).reshape(-1, 3)
|
||||
if verts.size == 0:
|
||||
return
|
||||
|
||||
faces = np.array(geom.faces, dtype=int).reshape(-1, 3)
|
||||
material_ids = np.array(geom.material_ids, dtype=int)
|
||||
|
||||
is_subject = highlight_ids is not None and shape.product.id() in highlight_ids
|
||||
|
||||
for midx, mat in enumerate(geom.materials):
|
||||
tri_mask = material_ids == midx
|
||||
if not np.any(tri_mask):
|
||||
continue
|
||||
|
||||
sub_faces = faces[tri_mask]
|
||||
faces_pv = np.hstack([np.full((sub_faces.shape[0], 1), 3, dtype=int), sub_faces]).ravel()
|
||||
mesh = pv.PolyData(verts, faces_pv)
|
||||
|
||||
if highlight_ids is not None and not is_subject:
|
||||
color = (180, 180, 180)
|
||||
opacity = 0.10
|
||||
else:
|
||||
diffuse = np.clip(np.array(mat.diffuse.components), 0.0, 1.0)
|
||||
color = tuple((diffuse * 255).astype(np.uint8))
|
||||
transparency = mat.transparency if mat.transparency == mat.transparency else 0.0
|
||||
opacity = float(np.clip(1.0 - transparency, 0.0, 1.0))
|
||||
|
||||
plotter.add_mesh(mesh, color=color, opacity=opacity, show_edges=False)
|
||||
|
||||
|
||||
def render(
|
||||
model: ifcopenshell.file,
|
||||
selector: str | None = None,
|
||||
element_ids: list[int] | None = None,
|
||||
view: str = "iso",
|
||||
) -> bytes:
|
||||
"""Render IFC model geometry to a PNG image.
|
||||
|
||||
:param model: The in-memory IFC model.
|
||||
:param selector: ifcopenshell selector to restrict rendered elements
|
||||
(e.g. ``'IfcWall'`` or ``'IfcBuildingStorey[Name="Ground Floor"]'``).
|
||||
When omitted the whole model is rendered.
|
||||
:param element_ids: Step IDs of elements to highlight. The rest of the
|
||||
model is rendered in translucent grey so the highlighted elements
|
||||
stand out.
|
||||
:param view: Camera angle: ``iso``, ``top``, ``south``, ``north``,
|
||||
``east``, or ``west``. Defaults to ``iso``.
|
||||
:return: PNG image as raw bytes.
|
||||
:raises ImportError: If pyvista is not installed.
|
||||
:raises ValueError: If the selector matches nothing or the model has no
|
||||
renderable geometry.
|
||||
"""
|
||||
if not _HAS_PYVISTA:
|
||||
raise ImportError("pyvista is not installed. Install with: pip install pyvista")
|
||||
|
||||
settings = ifcopenshell.geom.settings()
|
||||
settings.set("use-world-coords", True)
|
||||
|
||||
# Exclude 'Clearance' subcontexts (door/window operation zones) from rendering.
|
||||
clearance_ids = {
|
||||
c.id()
|
||||
for c in model.by_type("IfcGeometricRepresentationSubContext")
|
||||
if c.ContextIdentifier == "Clearance"
|
||||
}
|
||||
if clearance_ids:
|
||||
ctx_ids = [
|
||||
c.id()
|
||||
for c in model.by_type("IfcGeometricRepresentationContext")
|
||||
if c.id() not in clearance_ids
|
||||
]
|
||||
if ctx_ids:
|
||||
settings.set("context-ids", ctx_ids)
|
||||
|
||||
if selector:
|
||||
include_elements = list(ifcopenshell.util.selector.filter_elements(model, selector))
|
||||
if not include_elements:
|
||||
raise ValueError(f"Selector {selector!r} matched no elements")
|
||||
iterator = ifcopenshell.geom.iterator(
|
||||
settings,
|
||||
model,
|
||||
multiprocessing.cpu_count(),
|
||||
include=include_elements,
|
||||
)
|
||||
else:
|
||||
exclude = list(model.by_type("IfcOpeningElement"))
|
||||
iterator = ifcopenshell.geom.iterator(
|
||||
settings,
|
||||
model,
|
||||
multiprocessing.cpu_count(),
|
||||
exclude=exclude if exclude else None,
|
||||
)
|
||||
|
||||
if not iterator.initialize():
|
||||
raise ValueError("No renderable geometry found in model (or selector matched nothing)")
|
||||
|
||||
plotter = pv.Plotter(off_screen=True, window_size=(1280, 960))
|
||||
plotter.background_color = "white"
|
||||
|
||||
while True:
|
||||
_add_shape(iterator.get(), plotter, highlight_ids=frozenset(element_ids) if element_ids else None)
|
||||
if not iterator.next():
|
||||
break
|
||||
|
||||
plotter.reset_camera()
|
||||
_apply_view(plotter, view)
|
||||
|
||||
tmp_fd, tmp_path = tempfile.mkstemp(suffix=".png")
|
||||
os.close(tmp_fd)
|
||||
try:
|
||||
plotter.show(screenshot=tmp_path, auto_close=True)
|
||||
with open(tmp_path, "rb") as f:
|
||||
return f.read()
|
||||
finally:
|
||||
try:
|
||||
os.unlink(tmp_path)
|
||||
except OSError:
|
||||
pass
|
||||
@@ -0,0 +1,56 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import ifcopenshell
|
||||
import ifcopenshell.util.sequence as seq
|
||||
|
||||
|
||||
def _task_to_dict(task: ifcopenshell.entity_instance, max_depth: int | None, depth: int) -> dict[str, Any]:
|
||||
task_time = task.TaskTime
|
||||
start = None
|
||||
finish = None
|
||||
if task_time:
|
||||
start = task_time.ScheduleStart
|
||||
finish = task_time.ScheduleFinish
|
||||
|
||||
outputs = []
|
||||
for product in seq.get_task_outputs(task):
|
||||
outputs.append({"id": product.id(), "type": product.is_a(), "name": getattr(product, "Name", None)})
|
||||
|
||||
if max_depth is not None and depth >= max_depth:
|
||||
child_count = len(seq.get_nested_tasks(task))
|
||||
subtasks = {"truncated": True, "count": child_count} if child_count else []
|
||||
else:
|
||||
subtasks = [_task_to_dict(sub, max_depth, depth + 1) for sub in seq.get_nested_tasks(task)]
|
||||
|
||||
return {
|
||||
"id": task.id(),
|
||||
"name": getattr(task, "Name", None),
|
||||
"start": start,
|
||||
"finish": finish,
|
||||
"is_milestone": bool(task.IsMilestone) if hasattr(task, "IsMilestone") else False,
|
||||
"outputs": outputs,
|
||||
"subtasks": subtasks,
|
||||
}
|
||||
|
||||
|
||||
def schedule(model: ifcopenshell.file, max_depth: int | None = None) -> list[dict[str, Any]]:
|
||||
"""Return a list of IfcWorkSchedule entries with nested task trees.
|
||||
|
||||
max_depth limits how many levels of subtasks are expanded (None = unlimited).
|
||||
At the cutoff level, subtasks is replaced with {"truncated": True, "count": N}.
|
||||
"""
|
||||
result = []
|
||||
for work_schedule in model.by_type("IfcWorkSchedule"):
|
||||
tasks = [_task_to_dict(t, max_depth, depth=1) for t in seq.get_root_tasks(work_schedule)]
|
||||
result.append(
|
||||
{
|
||||
"id": work_schedule.id(),
|
||||
"name": getattr(work_schedule, "Name", None),
|
||||
"predefined_type": getattr(work_schedule, "PredefinedType", None),
|
||||
"tasks": tasks,
|
||||
}
|
||||
)
|
||||
return result
|
||||
@@ -0,0 +1,19 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import ifcopenshell
|
||||
import ifcopenshell.util.doc
|
||||
|
||||
|
||||
def schema(model: ifcopenshell.file, entity_type: str) -> dict[str, Any]:
|
||||
"""Return IFC class documentation for entity_type from model's schema version."""
|
||||
schema_name = model.schema
|
||||
try:
|
||||
doc = ifcopenshell.util.doc.get_entity_doc(schema_name, entity_type)
|
||||
except Exception:
|
||||
return {"error": f"Unknown entity: {entity_type}"}
|
||||
if not doc:
|
||||
return {"error": f"Unknown entity: {entity_type}"}
|
||||
return dict(doc)
|
||||
@@ -0,0 +1,15 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import ifcopenshell
|
||||
import ifcopenshell.validate
|
||||
|
||||
|
||||
def validate(model: ifcopenshell.file, express_rules: bool = False) -> dict[str, Any]:
|
||||
"""Validate the model and return a dict with 'valid' bool and 'issues' list."""
|
||||
logger = ifcopenshell.validate.json_logger()
|
||||
ifcopenshell.validate.validate(model, logger, express_rules=express_rules)
|
||||
issues = [{"level": s["level"], "message": s["message"]} for s in logger.statements]
|
||||
return {"valid": len(issues) == 0, "issues": issues}
|
||||
@@ -17,6 +17,9 @@ classifiers = [
|
||||
]
|
||||
dependencies = ["ifcopenshell"]
|
||||
|
||||
[project.scripts]
|
||||
ifcquery = "ifcquery.__main__:main"
|
||||
|
||||
[project.urls]
|
||||
Homepage = "http://ifcopenshell.org"
|
||||
Documentation = "https://docs.ifcopenshell.org"
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
from __future__ import annotations
|
||||
|
||||
import ifcopenshell
|
||||
import ifcopenshell.api.cost
|
||||
import ifcopenshell.api.owner.settings
|
||||
import ifcopenshell.api.project
|
||||
import ifcopenshell.api.root
|
||||
import ifcopenshell.api.unit
|
||||
import pytest
|
||||
|
||||
from ifcquery.cost import cost
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cost_model():
|
||||
"""Create an IFC4 model with a cost schedule, a top-level item, and one nested subitem."""
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
ifcopenshell.api.owner.settings.get_user = lambda ifc: (ifc.by_type("IfcPersonAndOrganization") or [None])[0]
|
||||
ifcopenshell.api.owner.settings.get_application = lambda ifc: (ifc.by_type("IfcApplication") or [None])[0]
|
||||
|
||||
project = ifcopenshell.api.root.create_entity(f, ifc_class="IfcProject", name="TestProject")
|
||||
ifcopenshell.api.unit.assign_unit(f)
|
||||
|
||||
cs = ifcopenshell.api.cost.add_cost_schedule(f, name="Bill of Quantities")
|
||||
item = ifcopenshell.api.cost.add_cost_item(f, cost_schedule=cs)
|
||||
ifcopenshell.api.cost.edit_cost_item(f, cost_item=item, attributes={"Name": "Concrete Works"})
|
||||
cv = ifcopenshell.api.cost.add_cost_value(f, parent=item)
|
||||
ifcopenshell.api.cost.edit_cost_value(f, cost_value=cv, attributes={"AppliedValue": 1200.0, "Category": "material"})
|
||||
|
||||
# Add a nested subitem
|
||||
subitem = ifcopenshell.api.cost.add_cost_item(f, cost_item=item)
|
||||
ifcopenshell.api.cost.edit_cost_item(f, cost_item=subitem, attributes={"Name": "Formwork"})
|
||||
|
||||
return f
|
||||
|
||||
|
||||
class TestCost:
|
||||
def test_returns_list(self, cost_model):
|
||||
result = cost(cost_model)
|
||||
assert isinstance(result, list)
|
||||
|
||||
def test_finds_cost_schedule(self, cost_model):
|
||||
result = cost(cost_model)
|
||||
assert len(result) == 1
|
||||
|
||||
def test_schedule_has_name(self, cost_model):
|
||||
result = cost(cost_model)
|
||||
assert result[0]["name"] == "Bill of Quantities"
|
||||
|
||||
def test_schedule_has_id(self, cost_model):
|
||||
result = cost(cost_model)
|
||||
assert isinstance(result[0]["id"], int)
|
||||
assert result[0]["id"] > 0
|
||||
|
||||
def test_schedule_has_items(self, cost_model):
|
||||
result = cost(cost_model)
|
||||
assert len(result[0]["items"]) == 1
|
||||
|
||||
def test_item_has_required_fields(self, cost_model):
|
||||
result = cost(cost_model)
|
||||
item = result[0]["items"][0]
|
||||
assert "id" in item
|
||||
assert "name" in item
|
||||
assert "values" in item
|
||||
assert "subitems" in item
|
||||
|
||||
def test_item_name(self, cost_model):
|
||||
result = cost(cost_model)
|
||||
assert result[0]["items"][0]["name"] == "Concrete Works"
|
||||
|
||||
def test_item_has_values(self, cost_model):
|
||||
result = cost(cost_model)
|
||||
values = result[0]["items"][0]["values"]
|
||||
assert len(values) == 1
|
||||
assert "formula" in values[0]
|
||||
assert "category" in values[0]
|
||||
|
||||
def test_item_value_category(self, cost_model):
|
||||
result = cost(cost_model)
|
||||
values = result[0]["items"][0]["values"]
|
||||
assert values[0]["category"] == "material"
|
||||
|
||||
def test_empty_model_returns_empty_list(self, model):
|
||||
result = cost(model)
|
||||
assert result == []
|
||||
|
||||
def test_max_depth_none_returns_full_tree(self, cost_model):
|
||||
result = cost(cost_model, max_depth=None)
|
||||
item = result[0]["items"][0]
|
||||
assert isinstance(item["subitems"], list)
|
||||
assert len(item["subitems"]) == 1
|
||||
assert item["subitems"][0]["name"] == "Formwork"
|
||||
|
||||
def test_max_depth_1_truncates_subitems(self, cost_model):
|
||||
result = cost(cost_model, max_depth=1)
|
||||
item = result[0]["items"][0]
|
||||
assert isinstance(item["subitems"], dict)
|
||||
assert item["subitems"]["truncated"] is True
|
||||
assert item["subitems"]["count"] == 1
|
||||
|
||||
def test_max_depth_2_expands_to_depth_2(self, cost_model):
|
||||
result = cost(cost_model, max_depth=2)
|
||||
item = result[0]["items"][0]
|
||||
assert isinstance(item["subitems"], list)
|
||||
assert item["subitems"][0]["name"] == "Formwork"
|
||||
# subitem has no children, so subitems should be empty list
|
||||
assert item["subitems"][0]["subitems"] == []
|
||||
@@ -0,0 +1,221 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
import ifcopenshell
|
||||
import ifcopenshell.api.aggregate
|
||||
import ifcopenshell.api.context
|
||||
import ifcopenshell.api.geometry
|
||||
import ifcopenshell.api.owner.settings
|
||||
import ifcopenshell.api.project
|
||||
import ifcopenshell.api.root
|
||||
import ifcopenshell.api.spatial
|
||||
import ifcopenshell.api.unit
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from ifcquery.render import render
|
||||
|
||||
try:
|
||||
import pyvista # noqa: F401
|
||||
|
||||
HAS_PYVISTA = True
|
||||
except ImportError:
|
||||
HAS_PYVISTA = False
|
||||
|
||||
pytestmark = pytest.mark.skipif(not HAS_PYVISTA, reason="pyvista not installed")
|
||||
|
||||
PNG_MAGIC = b"\x89PNG"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def model_with_geometry():
|
||||
"""Create an IFC4 model with walls that have geometric representations."""
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
ifcopenshell.api.owner.settings.get_user = lambda ifc: (ifc.by_type("IfcPersonAndOrganization") or [None])[0]
|
||||
ifcopenshell.api.owner.settings.get_application = lambda ifc: (ifc.by_type("IfcApplication") or [None])[0]
|
||||
|
||||
project = ifcopenshell.api.root.create_entity(f, ifc_class="IfcProject", name="TestProject")
|
||||
ifcopenshell.api.unit.assign_unit(f)
|
||||
|
||||
site = ifcopenshell.api.root.create_entity(f, ifc_class="IfcSite", name="TestSite")
|
||||
building = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuilding", name="TestBuilding")
|
||||
storey = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuildingStorey", name="Ground Floor")
|
||||
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[site], relating_object=project)
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[building], relating_object=site)
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[storey], relating_object=building)
|
||||
|
||||
model_ctx = ifcopenshell.api.context.add_context(f, context_type="Model")
|
||||
body = ifcopenshell.api.context.add_context(
|
||||
f, context_type="Model", context_identifier="Body", target_view="MODEL_VIEW", parent=model_ctx
|
||||
)
|
||||
|
||||
wall1 = ifcopenshell.api.root.create_entity(f, ifc_class="IfcWall", name="Wall001")
|
||||
rep1 = ifcopenshell.api.geometry.add_wall_representation(f, context=body, length=5, height=3, thickness=0.2)
|
||||
ifcopenshell.api.geometry.assign_representation(f, product=wall1, representation=rep1)
|
||||
ifcopenshell.api.spatial.assign_container(f, products=[wall1], relating_structure=storey)
|
||||
|
||||
wall2 = ifcopenshell.api.root.create_entity(f, ifc_class="IfcWall", name="Wall002")
|
||||
rep2 = ifcopenshell.api.geometry.add_wall_representation(f, context=body, length=4, height=3, thickness=0.2)
|
||||
ifcopenshell.api.geometry.assign_representation(f, product=wall2, representation=rep2)
|
||||
ifcopenshell.api.spatial.assign_container(f, products=[wall2], relating_structure=storey)
|
||||
matrix2 = np.eye(4)
|
||||
matrix2[1, 3] = 3.0
|
||||
ifcopenshell.api.geometry.edit_object_placement(f, product=wall2, matrix=matrix2)
|
||||
|
||||
return f
|
||||
|
||||
|
||||
class TestRenderBasic:
|
||||
def test_returns_png_bytes(self, model_with_geometry):
|
||||
result = render(model_with_geometry)
|
||||
assert isinstance(result, bytes)
|
||||
assert result[:4] == PNG_MAGIC
|
||||
|
||||
def test_iso_view(self, model_with_geometry):
|
||||
result = render(model_with_geometry, view="iso")
|
||||
assert result[:4] == PNG_MAGIC
|
||||
|
||||
def test_top_view(self, model_with_geometry):
|
||||
result = render(model_with_geometry, view="top")
|
||||
assert result[:4] == PNG_MAGIC
|
||||
|
||||
def test_south_view(self, model_with_geometry):
|
||||
result = render(model_with_geometry, view="south")
|
||||
assert result[:4] == PNG_MAGIC
|
||||
|
||||
def test_unknown_view_falls_back_to_iso(self, model_with_geometry):
|
||||
# Unknown view strings fall through to isometric
|
||||
result = render(model_with_geometry, view="diagonal")
|
||||
assert result[:4] == PNG_MAGIC
|
||||
|
||||
|
||||
class TestRenderSelector:
|
||||
def test_selector_restricts_elements(self, model_with_geometry):
|
||||
result = render(model_with_geometry, selector="IfcWall")
|
||||
assert result[:4] == PNG_MAGIC
|
||||
|
||||
def test_selector_no_match_raises(self, model_with_geometry):
|
||||
with pytest.raises(ValueError, match="matched no elements"):
|
||||
render(model_with_geometry, selector="IfcDoor")
|
||||
|
||||
|
||||
class TestRenderHighlight:
|
||||
def test_highlight_single_element(self, model_with_geometry):
|
||||
wall = model_with_geometry.by_type("IfcWall")[0]
|
||||
result = render(model_with_geometry, element_ids=[wall.id()])
|
||||
assert result[:4] == PNG_MAGIC
|
||||
|
||||
def test_highlight_multiple_elements(self, model_with_geometry):
|
||||
walls = model_with_geometry.by_type("IfcWall")
|
||||
result = render(model_with_geometry, element_ids=[w.id() for w in walls])
|
||||
assert result[:4] == PNG_MAGIC
|
||||
|
||||
|
||||
class TestRenderNoGeometry:
|
||||
def test_no_geometry_raises(self):
|
||||
"""A model without geometry representations raises ValueError."""
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
ifcopenshell.api.owner.settings.get_user = lambda ifc: (ifc.by_type("IfcPersonAndOrganization") or [None])[0]
|
||||
ifcopenshell.api.owner.settings.get_application = lambda ifc: (ifc.by_type("IfcApplication") or [None])[0]
|
||||
project = ifcopenshell.api.root.create_entity(f, ifc_class="IfcProject", name="P")
|
||||
ifcopenshell.api.unit.assign_unit(f)
|
||||
site = ifcopenshell.api.root.create_entity(f, ifc_class="IfcSite", name="S")
|
||||
building = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuilding", name="B")
|
||||
storey = ifcopenshell.api.root.create_entity(f, ifc_class="IfcBuildingStorey", name="GF")
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[site], relating_object=project)
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[building], relating_object=site)
|
||||
ifcopenshell.api.aggregate.assign_object(f, products=[storey], relating_object=building)
|
||||
wall = ifcopenshell.api.root.create_entity(f, ifc_class="IfcWall", name="Wallless")
|
||||
ifcopenshell.api.spatial.assign_container(f, products=[wall], relating_structure=storey)
|
||||
|
||||
with pytest.raises(ValueError, match="No renderable geometry"):
|
||||
render(f)
|
||||
|
||||
|
||||
class TestCLI:
|
||||
@staticmethod
|
||||
def _ifc_path(model):
|
||||
f = tempfile.NamedTemporaryFile(suffix=".ifc", delete=False)
|
||||
model.write(f.name)
|
||||
f.close()
|
||||
return f.name
|
||||
|
||||
def test_render_writes_png(self, model_with_geometry):
|
||||
ifc_path = self._ifc_path(model_with_geometry)
|
||||
out_path = ifc_path.replace(".ifc", "_out.png")
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "ifcquery", ifc_path, "render", "-o", out_path],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert os.path.exists(out_path)
|
||||
with open(out_path, "rb") as f:
|
||||
assert f.read(4) == PNG_MAGIC
|
||||
finally:
|
||||
for path in (ifc_path, out_path):
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def test_render_default_output_path(self, model_with_geometry):
|
||||
ifc_path = self._ifc_path(model_with_geometry)
|
||||
expected_png = ifc_path.replace(".ifc", ".png")
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "ifcquery", ifc_path, "render"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert os.path.exists(expected_png)
|
||||
finally:
|
||||
for path in (ifc_path, expected_png):
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def test_render_with_selector(self, model_with_geometry):
|
||||
ifc_path = self._ifc_path(model_with_geometry)
|
||||
out_path = ifc_path.replace(".ifc", "_sel.png")
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "ifcquery", ifc_path, "render", "-o", out_path, "--selector", "IfcWall"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
with open(out_path, "rb") as f:
|
||||
assert f.read(4) == PNG_MAGIC
|
||||
finally:
|
||||
for path in (ifc_path, out_path):
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def test_render_with_view(self, model_with_geometry):
|
||||
ifc_path = self._ifc_path(model_with_geometry)
|
||||
out_path = ifc_path.replace(".ifc", "_top.png")
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "ifcquery", ifc_path, "render", "-o", out_path, "--view", "top"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
with open(out_path, "rb") as f:
|
||||
assert f.read(4) == PNG_MAGIC
|
||||
finally:
|
||||
for path in (ifc_path, out_path):
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
@@ -0,0 +1,121 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
from __future__ import annotations
|
||||
|
||||
import ifcopenshell
|
||||
import ifcopenshell.api.aggregate
|
||||
import ifcopenshell.api.owner.settings
|
||||
import ifcopenshell.api.project
|
||||
import ifcopenshell.api.root
|
||||
import ifcopenshell.api.sequence
|
||||
import ifcopenshell.api.unit
|
||||
import pytest
|
||||
|
||||
from ifcquery.schedule import schedule
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def schedule_model():
|
||||
"""Create an IFC4 model with a work schedule and nested tasks."""
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
ifcopenshell.api.owner.settings.get_user = lambda ifc: (ifc.by_type("IfcPersonAndOrganization") or [None])[0]
|
||||
ifcopenshell.api.owner.settings.get_application = lambda ifc: (ifc.by_type("IfcApplication") or [None])[0]
|
||||
|
||||
project = ifcopenshell.api.root.create_entity(f, ifc_class="IfcProject", name="TestProject")
|
||||
ifcopenshell.api.unit.assign_unit(f)
|
||||
|
||||
ws = ifcopenshell.api.sequence.add_work_schedule(f, name="Construction Schedule")
|
||||
|
||||
task1 = ifcopenshell.api.sequence.add_task(f, work_schedule=ws, name="Phase 1", identification="P1")
|
||||
tt1 = ifcopenshell.api.sequence.add_task_time(f, task=task1)
|
||||
ifcopenshell.api.sequence.edit_task_time(
|
||||
f, task_time=tt1, attributes={"ScheduleStart": "2024-01-01", "ScheduleFinish": "2024-06-30"}
|
||||
)
|
||||
|
||||
task2 = ifcopenshell.api.sequence.add_task(f, work_schedule=ws, name="Phase 2", identification="P2")
|
||||
subtask = ifcopenshell.api.sequence.add_task(f, parent_task=task1, name="Sub Task", identification="S1")
|
||||
|
||||
return f
|
||||
|
||||
|
||||
class TestSchedule:
|
||||
def test_returns_list(self, schedule_model):
|
||||
result = schedule(schedule_model)
|
||||
assert isinstance(result, list)
|
||||
|
||||
def test_finds_work_schedule(self, schedule_model):
|
||||
result = schedule(schedule_model)
|
||||
assert len(result) == 1
|
||||
|
||||
def test_work_schedule_has_name(self, schedule_model):
|
||||
result = schedule(schedule_model)
|
||||
assert result[0]["name"] == "Construction Schedule"
|
||||
|
||||
def test_work_schedule_has_id(self, schedule_model):
|
||||
result = schedule(schedule_model)
|
||||
assert isinstance(result[0]["id"], int)
|
||||
assert result[0]["id"] > 0
|
||||
|
||||
def test_work_schedule_has_tasks(self, schedule_model):
|
||||
result = schedule(schedule_model)
|
||||
tasks = result[0]["tasks"]
|
||||
assert isinstance(tasks, list)
|
||||
assert len(tasks) >= 1
|
||||
|
||||
def test_task_has_required_fields(self, schedule_model):
|
||||
result = schedule(schedule_model)
|
||||
task = result[0]["tasks"][0]
|
||||
assert "id" in task
|
||||
assert "name" in task
|
||||
assert "start" in task
|
||||
assert "finish" in task
|
||||
assert "is_milestone" in task
|
||||
assert "outputs" in task
|
||||
assert "subtasks" in task
|
||||
|
||||
def test_task_name(self, schedule_model):
|
||||
result = schedule(schedule_model)
|
||||
task_names = [t["name"] for t in result[0]["tasks"]]
|
||||
assert "Phase 1" in task_names
|
||||
|
||||
def test_task_start_finish(self, schedule_model):
|
||||
result = schedule(schedule_model)
|
||||
phase1 = next(t for t in result[0]["tasks"] if t["name"] == "Phase 1")
|
||||
assert phase1["start"] is not None
|
||||
assert phase1["finish"] is not None
|
||||
|
||||
def test_subtasks(self, schedule_model):
|
||||
result = schedule(schedule_model)
|
||||
phase1 = next(t for t in result[0]["tasks"] if t["name"] == "Phase 1")
|
||||
assert len(phase1["subtasks"]) == 1
|
||||
assert phase1["subtasks"][0]["name"] == "Sub Task"
|
||||
|
||||
def test_empty_model_returns_empty_list(self, model):
|
||||
result = schedule(model)
|
||||
assert result == []
|
||||
|
||||
def test_max_depth_none_returns_full_tree(self, schedule_model):
|
||||
result = schedule(schedule_model, max_depth=None)
|
||||
phase1 = next(t for t in result[0]["tasks"] if t["name"] == "Phase 1")
|
||||
assert isinstance(phase1["subtasks"], list)
|
||||
assert len(phase1["subtasks"]) == 1
|
||||
|
||||
def test_max_depth_1_truncates_subtasks(self, schedule_model):
|
||||
result = schedule(schedule_model, max_depth=1)
|
||||
phase1 = next(t for t in result[0]["tasks"] if t["name"] == "Phase 1")
|
||||
assert isinstance(phase1["subtasks"], dict)
|
||||
assert phase1["subtasks"]["truncated"] is True
|
||||
assert phase1["subtasks"]["count"] == 1
|
||||
|
||||
def test_max_depth_truncation_shows_count(self, schedule_model):
|
||||
result = schedule(schedule_model, max_depth=1)
|
||||
# Phase 2 has no subtasks — should return empty list, not truncation dict
|
||||
phase2 = next(t for t in result[0]["tasks"] if t["name"] == "Phase 2")
|
||||
assert phase2["subtasks"] == []
|
||||
|
||||
def test_max_depth_2_expands_to_depth_2(self, schedule_model):
|
||||
result = schedule(schedule_model, max_depth=2)
|
||||
phase1 = next(t for t in result[0]["tasks"] if t["name"] == "Phase 1")
|
||||
# subtask at depth 2 should be fully expanded (it has no children)
|
||||
assert isinstance(phase1["subtasks"], list)
|
||||
assert phase1["subtasks"][0]["name"] == "Sub Task"
|
||||
assert phase1["subtasks"][0]["subtasks"] == []
|
||||
@@ -0,0 +1,32 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from ifcquery.schema import schema
|
||||
|
||||
|
||||
class TestSchema:
|
||||
def test_ifc_wall_has_description(self, model):
|
||||
result = schema(model, "IfcWall")
|
||||
assert "description" in result
|
||||
assert isinstance(result["description"], str)
|
||||
assert len(result["description"]) > 0
|
||||
|
||||
def test_ifc_wall_has_attributes(self, model):
|
||||
result = schema(model, "IfcWall")
|
||||
assert "attributes" in result
|
||||
|
||||
def test_ifc_wall_has_spec_url(self, model):
|
||||
result = schema(model, "IfcWall")
|
||||
assert "spec_url" in result
|
||||
|
||||
def test_unknown_entity_returns_error(self, model):
|
||||
result = schema(model, "IfcNonExistentFooBar")
|
||||
assert "error" in result
|
||||
assert "IfcNonExistentFooBar" in result["error"]
|
||||
|
||||
def test_ifc_window_has_description(self, model):
|
||||
result = schema(model, "IfcWindow")
|
||||
assert "description" in result
|
||||
assert len(result["description"]) > 0
|
||||
@@ -0,0 +1,47 @@
|
||||
# This file was generated with the assistance of an AI coding tool.
|
||||
from __future__ import annotations
|
||||
|
||||
import ifcopenshell
|
||||
import ifcopenshell.api.project
|
||||
import pytest
|
||||
|
||||
from ifcquery.validate import validate
|
||||
|
||||
|
||||
class TestValidate:
|
||||
def test_valid_model_returns_valid_true(self, model):
|
||||
result = validate(model)
|
||||
assert result["valid"] is True
|
||||
assert isinstance(result["issues"], list)
|
||||
|
||||
def test_valid_model_has_no_issues(self, model):
|
||||
result = validate(model)
|
||||
assert result["issues"] == []
|
||||
|
||||
def test_empty_model_is_valid(self):
|
||||
f = ifcopenshell.api.project.create_file()
|
||||
result = validate(f)
|
||||
assert result["valid"] is True
|
||||
assert result["issues"] == []
|
||||
|
||||
def test_result_has_expected_keys(self, model):
|
||||
result = validate(model)
|
||||
assert "valid" in result
|
||||
assert "issues" in result
|
||||
|
||||
def test_express_rules_flag_accepted(self, model):
|
||||
# Just verify it runs without error; express rules may add/not add issues
|
||||
result = validate(model, express_rules=True)
|
||||
assert "valid" in result
|
||||
assert isinstance(result["issues"], list)
|
||||
|
||||
def test_issue_has_level_and_message(self, model):
|
||||
# Force an issue by manually breaking the model (invalid IfcWall attribute)
|
||||
f = ifcopenshell.file()
|
||||
# Create a raw IfcWall with deliberately wrong type for GlobalId (use int)
|
||||
# We just check structure if any issues appear; on well-formed models there are none.
|
||||
result = validate(model)
|
||||
# Even if no issues, the structure contract must hold for any issues present
|
||||
for issue in result["issues"]:
|
||||
assert "level" in issue
|
||||
assert "message" in issue
|
||||
Reference in New Issue
Block a user